Merge branch 'master' into blender2.8
[blender.git] / source / blender / blenloader / intern / writefile.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  *
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/blenloader/intern/writefile.c
28  *  \ingroup blenloader
29  */
30
31
32 /**
33  *
34  * FILE FORMAT
35  * ===========
36  *
37  * IFF-style structure  (but not IFF compatible!)
38  *
39  * start file:
40  * <pre>
41  *     BLENDER_V100    12 bytes  (versie 1.00)
42  *                     V = big endian, v = little endian
43  *                     _ = 4 byte pointer, - = 8 byte pointer
44  * </pre>
45  *
46  * datablocks: (also see struct #BHead).
47  * <pre>
48  *     <bh.code>           4 chars
49  *     <bh.len>            int,  len data after BHead
50  *     <bh.old>            void,  old pointer
51  *     <bh.SDNAnr>         int
52  *     <bh.nr>             int, in case of array: number of structs
53  *     data
54  *     ...
55  *     ...
56  * </pre>
57  *
58  * Almost all data in Blender are structures. Each struct saved
59  * gets a BHead header.  With BHead the struct can be linked again
60  * and compared with StructDNA .
61  *
62  *
63  * WRITE
64  * =====
65  *
66  * Preferred writing order: (not really a must, but why would you do it random?)
67  * Any case: direct data is ALWAYS after the lib block
68  *
69  * (Local file data)
70  * - for each LibBlock
71  *   - write LibBlock
72  *   - write associated direct data
73  * (External file data)
74  * - per library
75  *   - write library block
76  *   - per LibBlock
77  *     - write the ID of LibBlock
78  * - write #TEST (#RenderInfo struct. 128x128 blend file preview is optional).
79  * - write #GLOB (#FileGlobal struct) (some global vars).
80  * - write #DNA1 (#SDNA struct)
81  * - write #USER (#UserDef struct) if filename is ``~/.config/blender/X.XX/config/startup.blend``.
82  */
83
84
85 #include <math.h>
86 #include <fcntl.h>
87 #include <limits.h>
88 #include <stdio.h>
89 #include <string.h>
90 #include <stdlib.h>
91
92 #ifdef WIN32
93 #  include <zlib.h>  /* odd include order-issue */
94 #  include "winsock2.h"
95 #  include <io.h>
96 #  include "BLI_winstuff.h"
97 #else
98 #  include <unistd.h>  /* FreeBSD, for write() and close(). */
99 #endif
100
101 #include "BLI_utildefines.h"
102
103 /* allow writefile to use deprecated functionality (for forward compatibility code) */
104 #define DNA_DEPRECATED_ALLOW
105 /* Allow using DNA struct members that are marked as private for read/write.
106  * Note: Each header that uses this needs to define its own way of handling
107  * it. There's no generic implementation, direct use does nothing. */
108 #define DNA_PRIVATE_READ_WRITE_ALLOW
109
110 #include "DNA_anim_types.h"
111 #include "DNA_armature_types.h"
112 #include "DNA_brush_types.h"
113 #include "DNA_cachefile_types.h"
114 #include "DNA_camera_types.h"
115 #include "DNA_cloth_types.h"
116 #include "DNA_collection_types.h"
117 #include "DNA_constraint_types.h"
118 #include "DNA_dynamicpaint_types.h"
119 #include "DNA_genfile.h"
120 #include "DNA_gpencil_types.h"
121 #include "DNA_gpencil_modifier_types.h"
122 #include "DNA_shader_fx_types.h"
123 #include "DNA_fileglobal_types.h"
124 #include "DNA_key_types.h"
125 #include "DNA_lattice_types.h"
126 #include "DNA_lamp_types.h"
127 #include "DNA_layer_types.h"
128 #include "DNA_linestyle_types.h"
129 #include "DNA_meta_types.h"
130 #include "DNA_mesh_types.h"
131 #include "DNA_meshdata_types.h"
132 #include "DNA_material_types.h"
133 #include "DNA_node_types.h"
134 #include "DNA_object_types.h"
135 #include "DNA_object_force_types.h"
136 #include "DNA_packedFile_types.h"
137 #include "DNA_particle_types.h"
138 #include "DNA_lightprobe_types.h"
139 #include "DNA_rigidbody_types.h"
140 #include "DNA_scene_types.h"
141 #include "DNA_sdna_types.h"
142 #include "DNA_sequence_types.h"
143 #include "DNA_smoke_types.h"
144 #include "DNA_space_types.h"
145 #include "DNA_screen_types.h"
146 #include "DNA_speaker_types.h"
147 #include "DNA_sound_types.h"
148 #include "DNA_text_types.h"
149 #include "DNA_view3d_types.h"
150 #include "DNA_vfont_types.h"
151 #include "DNA_world_types.h"
152 #include "DNA_windowmanager_types.h"
153 #include "DNA_workspace_types.h"
154 #include "DNA_movieclip_types.h"
155 #include "DNA_mask_types.h"
156
157 #include "MEM_guardedalloc.h" // MEM_freeN
158 #include "BLI_bitmap.h"
159 #include "BLI_blenlib.h"
160 #include "BLI_linklist.h"
161 #include "BLI_mempool.h"
162
163 #include "BKE_action.h"
164 #include "BKE_blender_version.h"
165 #include "BKE_bpath.h"
166 #include "BKE_collection.h"
167 #include "BKE_constraint.h"
168 #include "BKE_curve.h"
169 #include "BKE_fcurve.h"
170 #include "BKE_global.h" // for G
171 #include "BKE_gpencil_modifier.h"
172 #include "BKE_idcode.h"
173 #include "BKE_layer.h"
174 #include "BKE_library_override.h"
175 #include "BKE_main.h"
176 #include "BKE_mesh.h"
177 #include "BKE_modifier.h"
178 #include "BKE_node.h"
179 #include "BKE_pointcache.h"
180 #include "BKE_report.h"
181 #include "BKE_sequencer.h"
182 #include "BKE_shader_fx.h"
183 #include "BKE_subsurf.h"
184 #include "BKE_workspace.h"
185
186 #ifdef USE_NODE_COMPAT_CUSTOMNODES
187 #include "NOD_socket.h"  /* for sock->default_value data */
188 #endif
189
190
191 #include "BLO_writefile.h"
192 #include "BLO_readfile.h"
193 #include "BLO_undofile.h"
194 #include "BLO_blend_defs.h"
195
196 #include "readfile.h"
197
198 /* for SDNA_TYPE_FROM_STRUCT() macro */
199 #include "dna_type_offsets.h"
200
201 #include <errno.h>
202
203 /* ********* my write, buffered writing with minimum size chunks ************ */
204
205 /* Use optimal allocation since blocks of this size are kept in memory for undo. */
206 #define MYWRITE_BUFFER_SIZE (MEM_SIZE_OPTIMAL(1 << 17))  /* 128kb */
207 #define MYWRITE_MAX_CHUNK   (MEM_SIZE_OPTIMAL(1 << 15))  /* ~32kb */
208
209 /** Use if we want to store how many bytes have been written to the file. */
210 // #define USE_WRITE_DATA_LEN
211
212 /* -------------------------------------------------------------------- */
213 /** \name Internal Write Wrapper's (Abstracts Compression)
214  * \{ */
215
216 typedef enum {
217         WW_WRAP_NONE = 1,
218         WW_WRAP_ZLIB,
219 } eWriteWrapType;
220
221 typedef struct WriteWrap WriteWrap;
222 struct WriteWrap {
223         /* callbacks */
224         bool   (*open)(WriteWrap *ww, const char *filepath);
225         bool   (*close)(WriteWrap *ww);
226         size_t (*write)(WriteWrap *ww, const char *data, size_t data_len);
227
228         /* internal */
229         union {
230                 int file_handle;
231                 gzFile gz_handle;
232         } _user_data;
233 };
234
235 /* none */
236 #define FILE_HANDLE(ww) \
237         (ww)->_user_data.file_handle
238
239 static bool ww_open_none(WriteWrap *ww, const char *filepath)
240 {
241         int file;
242
243         file = BLI_open(filepath, O_BINARY + O_WRONLY + O_CREAT + O_TRUNC, 0666);
244
245         if (file != -1) {
246                 FILE_HANDLE(ww) = file;
247                 return true;
248         }
249         else {
250                 return false;
251         }
252 }
253 static bool ww_close_none(WriteWrap *ww)
254 {
255         return (close(FILE_HANDLE(ww)) != -1);
256 }
257 static size_t ww_write_none(WriteWrap *ww, const char *buf, size_t buf_len)
258 {
259         return write(FILE_HANDLE(ww), buf, buf_len);
260 }
261 #undef FILE_HANDLE
262
263 /* zlib */
264 #define FILE_HANDLE(ww) \
265         (ww)->_user_data.gz_handle
266
267 static bool ww_open_zlib(WriteWrap *ww, const char *filepath)
268 {
269         gzFile file;
270
271         file = BLI_gzopen(filepath, "wb1");
272
273         if (file != Z_NULL) {
274                 FILE_HANDLE(ww) = file;
275                 return true;
276         }
277         else {
278                 return false;
279         }
280 }
281 static bool ww_close_zlib(WriteWrap *ww)
282 {
283         return (gzclose(FILE_HANDLE(ww)) == Z_OK);
284 }
285 static size_t ww_write_zlib(WriteWrap *ww, const char *buf, size_t buf_len)
286 {
287         return gzwrite(FILE_HANDLE(ww), buf, buf_len);
288 }
289 #undef FILE_HANDLE
290
291 /* --- end compression types --- */
292
293 static void ww_handle_init(eWriteWrapType ww_type, WriteWrap *r_ww)
294 {
295         memset(r_ww, 0, sizeof(*r_ww));
296
297         switch (ww_type) {
298                 case WW_WRAP_ZLIB:
299                 {
300                         r_ww->open  = ww_open_zlib;
301                         r_ww->close = ww_close_zlib;
302                         r_ww->write = ww_write_zlib;
303                         break;
304                 }
305                 default:
306                 {
307                         r_ww->open  = ww_open_none;
308                         r_ww->close = ww_close_none;
309                         r_ww->write = ww_write_none;
310                         break;
311                 }
312         }
313 }
314
315 /** \} */
316
317 /* -------------------------------------------------------------------- */
318 /** \name Write Data Type & Functions
319  * \{ */
320
321 typedef struct {
322         const struct SDNA *sdna;
323
324         /** Use for file and memory writing (fixed size of #MYWRITE_BUFFER_SIZE). */
325         uchar *buf;
326         /** Number of bytes used in #WriteData.buf (flushed when exceeded). */
327         int buf_used_len;
328
329 #ifdef USE_WRITE_DATA_LEN
330         /** Total number of bytes written. */
331         size_t write_len;
332 #endif
333
334         /** Set on unlikely case of an error (ignores further file writing).  */
335         bool error;
336
337         /** #MemFile writing (used for undo). */
338         struct {
339                 MemFile      *current;
340                 MemFile      *compare;
341                 /** Use to de-duplicate chunks when writing. */
342                 MemFileChunk *compare_chunk;
343         } mem;
344         /** When true, write to #WriteData.current, could also call 'is_undo'. */
345         bool use_memfile;
346
347         /**
348          * Wrap writing, so we can use zlib or
349          * other compression types later, see: G_FILE_COMPRESS
350          * Will be NULL for UNDO.
351          */
352         WriteWrap *ww;
353 } WriteData;
354
355 static WriteData *writedata_new(WriteWrap *ww)
356 {
357         WriteData *wd = MEM_callocN(sizeof(*wd), "writedata");
358
359         wd->sdna = DNA_sdna_current_get();
360
361         wd->ww = ww;
362
363         wd->buf = MEM_mallocN(MYWRITE_BUFFER_SIZE, "wd->buf");
364
365         return wd;
366 }
367
368 static void writedata_do_write(WriteData *wd, const void *mem, int memlen)
369 {
370         if ((wd == NULL) || wd->error || (mem == NULL) || memlen < 1) {
371                 return;
372         }
373
374         if (UNLIKELY(wd->error)) {
375                 return;
376         }
377
378         /* memory based save */
379         if (wd->use_memfile) {
380                 memfile_chunk_add(wd->mem.current, mem, memlen, &wd->mem.compare_chunk);
381         }
382         else {
383                 if (wd->ww->write(wd->ww, mem, memlen) != memlen) {
384                         wd->error = true;
385                 }
386         }
387 }
388
389 static void writedata_free(WriteData *wd)
390 {
391         MEM_freeN(wd->buf);
392         MEM_freeN(wd);
393 }
394
395 /** \} */
396
397 /* -------------------------------------------------------------------- */
398 /** \name Local Writing API 'mywrite'
399  * \{ */
400
401 /**
402  * Flush helps the de-duplicating memory for undo-save by logically segmenting data,
403  * so differences in one part of memory won't cause unrelated data to be duplicated.
404  */
405 static void mywrite_flush(WriteData *wd)
406 {
407         if (wd->buf_used_len) {
408                 writedata_do_write(wd, wd->buf, wd->buf_used_len);
409                 wd->buf_used_len = 0;
410         }
411 }
412
413 /**
414  * Low level WRITE(2) wrapper that buffers data
415  * \param adr Pointer to new chunk of data
416  * \param len Length of new chunk of data
417  */
418 static void mywrite(WriteData *wd, const void *adr, int len)
419 {
420         if (UNLIKELY(wd->error)) {
421                 return;
422         }
423
424         if (UNLIKELY(adr == NULL)) {
425                 BLI_assert(0);
426                 return;
427         }
428
429 #ifdef USE_WRITE_DATA_LEN
430         wd->write_len += len;
431 #endif
432
433         /* if we have a single big chunk, write existing data in
434          * buffer and write out big chunk in smaller pieces */
435         if (len > MYWRITE_MAX_CHUNK) {
436                 if (wd->buf_used_len) {
437                         writedata_do_write(wd, wd->buf, wd->buf_used_len);
438                         wd->buf_used_len = 0;
439                 }
440
441                 do {
442                         int writelen = MIN2(len, MYWRITE_MAX_CHUNK);
443                         writedata_do_write(wd, adr, writelen);
444                         adr = (const char *)adr + writelen;
445                         len -= writelen;
446                 } while (len > 0);
447
448                 return;
449         }
450
451         /* if data would overflow buffer, write out the buffer */
452         if (len + wd->buf_used_len > MYWRITE_BUFFER_SIZE - 1) {
453                 writedata_do_write(wd, wd->buf, wd->buf_used_len);
454                 wd->buf_used_len = 0;
455         }
456
457         /* append data at end of buffer */
458         memcpy(&wd->buf[wd->buf_used_len], adr, len);
459         wd->buf_used_len += len;
460 }
461
462 /**
463  * BeGiN initializer for mywrite
464  * \param ww: File write wrapper.
465  * \param compare Previous memory file (can be NULL).
466  * \param current The current memory file (can be NULL).
467  * \warning Talks to other functions with global parameters
468  */
469 static WriteData *mywrite_begin(WriteWrap *ww, MemFile *compare, MemFile *current)
470 {
471         WriteData *wd = writedata_new(ww);
472
473         if (current != NULL) {
474                 wd->mem.current = current;
475                 wd->mem.compare = compare;
476                 wd->mem.compare_chunk = compare ? compare->chunks.first : NULL;
477                 wd->use_memfile = true;
478         }
479
480         return wd;
481 }
482
483 /**
484  * END the mywrite wrapper
485  * \return 1 if write failed
486  * \return unknown global variable otherwise
487  * \warning Talks to other functions with global parameters
488  */
489 static bool mywrite_end(WriteData *wd)
490 {
491         if (wd->buf_used_len) {
492                 writedata_do_write(wd, wd->buf, wd->buf_used_len);
493                 wd->buf_used_len = 0;
494         }
495
496         const bool err = wd->error;
497         writedata_free(wd);
498
499         return err;
500 }
501
502 /** \} */
503
504 /* -------------------------------------------------------------------- */
505 /** \name Generic DNA File Writing
506  * \{ */
507
508 static void writestruct_at_address_nr(
509         WriteData *wd, int filecode, const int struct_nr, int nr,
510         const void *adr, const void *data)
511 {
512         BHead bh;
513         const short *sp;
514
515         BLI_assert(struct_nr > 0 && struct_nr < SDNA_TYPE_MAX);
516
517         if (adr == NULL || data == NULL || nr == 0) {
518                 return;
519         }
520
521         /* init BHead */
522         bh.code = filecode;
523         bh.old = adr;
524         bh.nr = nr;
525
526         bh.SDNAnr = struct_nr;
527         sp = wd->sdna->structs[bh.SDNAnr];
528
529         bh.len = nr * wd->sdna->typelens[sp[0]];
530
531         if (bh.len == 0) {
532                 return;
533         }
534
535         mywrite(wd, &bh, sizeof(BHead));
536         mywrite(wd, data, bh.len);
537 }
538
539 static void writestruct_at_address_id(
540         WriteData *wd, int filecode, const char *structname, int nr,
541         const void *adr, const void *data)
542 {
543         if (adr == NULL || data == NULL || nr == 0) {
544                 return;
545         }
546
547         const int SDNAnr = DNA_struct_find_nr(wd->sdna, structname);
548         if (UNLIKELY(SDNAnr == -1)) {
549                 printf("error: can't find SDNA code <%s>\n", structname);
550                 return;
551         }
552
553         writestruct_at_address_nr(wd, filecode, SDNAnr, nr, adr, data);
554 }
555
556 static void writestruct_nr(
557         WriteData *wd, int filecode, const int struct_nr, int nr,
558         const void *adr)
559 {
560         writestruct_at_address_nr(wd, filecode, struct_nr, nr, adr, adr);
561 }
562
563 static void writestruct_id(
564         WriteData *wd, int filecode, const char *structname, int nr,
565         const void *adr)
566 {
567         writestruct_at_address_id(wd, filecode, structname, nr, adr, adr);
568 }
569
570 static void writedata(WriteData *wd, int filecode, int len, const void *adr)  /* do not use for structs */
571 {
572         BHead bh;
573
574         if (adr == NULL || len == 0) {
575                 return;
576         }
577
578         /* align to 4 (writes uninitialized bytes in some cases) */
579         len = (len + 3) & ~3;
580
581         /* init BHead */
582         bh.code   = filecode;
583         bh.old    = adr;
584         bh.nr     = 1;
585         bh.SDNAnr = 0;
586         bh.len    = len;
587
588         mywrite(wd, &bh, sizeof(BHead));
589         mywrite(wd, adr, len);
590 }
591
592 /* use this to force writing of lists in same order as reading (using link_list) */
593 static void writelist_nr(WriteData *wd, int filecode, const int struct_nr, const ListBase *lb)
594 {
595         const Link *link = lb->first;
596
597         while (link) {
598                 writestruct_nr(wd, filecode, struct_nr, 1, link);
599                 link = link->next;
600         }
601 }
602
603 #if 0
604 static void writelist_id(WriteData *wd, int filecode, const char *structname, const ListBase *lb)
605 {
606         const Link *link = lb->first;
607         if (link) {
608
609                 const int struct_nr = DNA_struct_find_nr(wd->sdna, structname);
610                 if (struct_nr == -1) {
611                         printf("error: can't find SDNA code <%s>\n", structname);
612                         return;
613                 }
614
615                 while (link) {
616                         writestruct_nr(wd, filecode, struct_nr, 1, link);
617                         link = link->next;
618                 }
619         }
620 }
621 #endif
622
623 #define writestruct_at_address(wd, filecode, struct_id, nr, adr, data) \
624         writestruct_at_address_nr(wd, filecode, SDNA_TYPE_FROM_STRUCT(struct_id), nr, adr, data)
625
626 #define writestruct(wd, filecode, struct_id, nr, adr) \
627         writestruct_nr(wd, filecode, SDNA_TYPE_FROM_STRUCT(struct_id), nr, adr)
628
629 #define writelist(wd, filecode, struct_id, lb) \
630         writelist_nr(wd, filecode, SDNA_TYPE_FROM_STRUCT(struct_id), lb)
631
632 /** \} */
633
634 /* -------------------------------------------------------------------- */
635 /** \name Typed DNA File Writing
636  *
637  * These functions are used by blender's .blend system for file saving/loading.
638  * \{ */
639
640 void IDP_WriteProperty_OnlyData(const IDProperty *prop, void *wd);
641 void IDP_WriteProperty(const IDProperty *prop, void *wd);
642
643 static void IDP_WriteArray(const IDProperty *prop, void *wd)
644 {
645         /*REMEMBER to set totalen to len in the linking code!!*/
646         if (prop->data.pointer) {
647                 writedata(wd, DATA, MEM_allocN_len(prop->data.pointer), prop->data.pointer);
648
649                 if (prop->subtype == IDP_GROUP) {
650                         IDProperty **array = prop->data.pointer;
651                         int a;
652
653                         for (a = 0; a < prop->len; a++) {
654                                 IDP_WriteProperty(array[a], wd);
655                         }
656                 }
657         }
658 }
659
660 static void IDP_WriteIDPArray(const IDProperty *prop, void *wd)
661 {
662         /*REMEMBER to set totalen to len in the linking code!!*/
663         if (prop->data.pointer) {
664                 const IDProperty *array = prop->data.pointer;
665                 int a;
666
667                 writestruct(wd, DATA, IDProperty, prop->len, array);
668
669                 for (a = 0; a < prop->len; a++) {
670                         IDP_WriteProperty_OnlyData(&array[a], wd);
671                 }
672         }
673 }
674
675 static void IDP_WriteString(const IDProperty *prop, void *wd)
676 {
677         /*REMEMBER to set totalen to len in the linking code!!*/
678         writedata(wd, DATA, prop->len, prop->data.pointer);
679 }
680
681 static void IDP_WriteGroup(const IDProperty *prop, void *wd)
682 {
683         IDProperty *loop;
684
685         for (loop = prop->data.group.first; loop; loop = loop->next) {
686                 IDP_WriteProperty(loop, wd);
687         }
688 }
689
690 /* Functions to read/write ID Properties */
691 void IDP_WriteProperty_OnlyData(const IDProperty *prop, void *wd)
692 {
693         switch (prop->type) {
694                 case IDP_GROUP:
695                         IDP_WriteGroup(prop, wd);
696                         break;
697                 case IDP_STRING:
698                         IDP_WriteString(prop, wd);
699                         break;
700                 case IDP_ARRAY:
701                         IDP_WriteArray(prop, wd);
702                         break;
703                 case IDP_IDPARRAY:
704                         IDP_WriteIDPArray(prop, wd);
705                         break;
706         }
707 }
708
709 void IDP_WriteProperty(const IDProperty *prop, void *wd)
710 {
711         writestruct(wd, DATA, IDProperty, 1, prop);
712         IDP_WriteProperty_OnlyData(prop, wd);
713 }
714
715 static void write_iddata(void *wd, const ID *id)
716 {
717         /* ID_WM's id->properties are considered runtime only, and never written in .blend file. */
718         if (id->properties && !ELEM(GS(id->name), ID_WM)) {
719                 IDP_WriteProperty(id->properties, wd);
720         }
721
722         if (id->override_static) {
723                 writestruct(wd, DATA, IDOverrideStatic, 1, id->override_static);
724
725                 writelist(wd, DATA, IDOverrideStaticProperty, &id->override_static->properties);
726                 for (IDOverrideStaticProperty *op = id->override_static->properties.first; op; op = op->next) {
727                         writedata(wd, DATA, strlen(op->rna_path) + 1, op->rna_path);
728
729                         writelist(wd, DATA, IDOverrideStaticPropertyOperation, &op->operations);
730                         for (IDOverrideStaticPropertyOperation *opop = op->operations.first; opop; opop = opop->next) {
731                                 if (opop->subitem_reference_name) {
732                                         writedata(wd, DATA, strlen(opop->subitem_reference_name) + 1, opop->subitem_reference_name);
733                                 }
734                                 if (opop->subitem_local_name) {
735                                         writedata(wd, DATA, strlen(opop->subitem_local_name) + 1, opop->subitem_local_name);
736                                 }
737                         }
738                 }
739         }
740 }
741
742 static void write_previews(WriteData *wd, const PreviewImage *prv_orig)
743 {
744         /* Note we write previews also for undo steps. It takes up some memory,
745          * but not doing so would causes all previews to be re-rendered after
746          * undo which is too expensive. */
747         if (prv_orig) {
748                 PreviewImage prv = *prv_orig;
749
750                 /* don't write out large previews if not requested */
751                 if (!(U.flag & USER_SAVE_PREVIEWS)) {
752                         prv.w[1] = 0;
753                         prv.h[1] = 0;
754                         prv.rect[1] = NULL;
755                 }
756                 writestruct_at_address(wd, DATA, PreviewImage, 1, prv_orig, &prv);
757                 if (prv.rect[0]) {
758                         writedata(wd, DATA, prv.w[0] * prv.h[0] * sizeof(uint), prv.rect[0]);
759                 }
760                 if (prv.rect[1]) {
761                         writedata(wd, DATA, prv.w[1] * prv.h[1] * sizeof(uint), prv.rect[1]);
762                 }
763         }
764 }
765
766 static void write_fmodifiers(WriteData *wd, ListBase *fmodifiers)
767 {
768         FModifier *fcm;
769
770         /* Write all modifiers first (for faster reloading) */
771         writelist(wd, DATA, FModifier, fmodifiers);
772
773         /* Modifiers */
774         for (fcm = fmodifiers->first; fcm; fcm = fcm->next) {
775                 const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(fcm);
776
777                 /* Write the specific data */
778                 if (fmi && fcm->data) {
779                         /* firstly, just write the plain fmi->data struct */
780                         writestruct_id(wd, DATA, fmi->structName, 1, fcm->data);
781
782                         /* do any modifier specific stuff */
783                         switch (fcm->type) {
784                                 case FMODIFIER_TYPE_GENERATOR:
785                                 {
786                                         FMod_Generator *data = fcm->data;
787
788                                         /* write coefficients array */
789                                         if (data->coefficients) {
790                                                 writedata(wd, DATA, sizeof(float) * (data->arraysize), data->coefficients);
791                                         }
792
793                                         break;
794                                 }
795                                 case FMODIFIER_TYPE_ENVELOPE:
796                                 {
797                                         FMod_Envelope *data = fcm->data;
798
799                                         /* write envelope data */
800                                         if (data->data) {
801                                                 writestruct(wd, DATA, FCM_EnvelopeData, data->totvert, data->data);
802                                         }
803
804                                         break;
805                                 }
806                                 case FMODIFIER_TYPE_PYTHON:
807                                 {
808                                         FMod_Python *data = fcm->data;
809
810                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
811                                          * of library blocks that implement this.*/
812                                         IDP_WriteProperty(data->prop, wd);
813
814                                         break;
815                                 }
816                         }
817                 }
818         }
819 }
820
821 static void write_fcurves(WriteData *wd, ListBase *fcurves)
822 {
823         FCurve *fcu;
824
825         writelist(wd, DATA, FCurve, fcurves);
826         for (fcu = fcurves->first; fcu; fcu = fcu->next) {
827                 /* curve data */
828                 if (fcu->bezt) {
829                         writestruct(wd, DATA, BezTriple, fcu->totvert, fcu->bezt);
830                 }
831                 if (fcu->fpt) {
832                         writestruct(wd, DATA, FPoint, fcu->totvert, fcu->fpt);
833                 }
834
835                 if (fcu->rna_path) {
836                         writedata(wd, DATA, strlen(fcu->rna_path) + 1, fcu->rna_path);
837                 }
838
839                 /* driver data */
840                 if (fcu->driver) {
841                         ChannelDriver *driver = fcu->driver;
842                         DriverVar *dvar;
843
844                         writestruct(wd, DATA, ChannelDriver, 1, driver);
845
846                         /* variables */
847                         writelist(wd, DATA, DriverVar, &driver->variables);
848                         for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
849                                 DRIVER_TARGETS_USED_LOOPER_BEGIN(dvar)
850                                 {
851                                         if (dtar->rna_path) {
852                                                 writedata(wd, DATA, strlen(dtar->rna_path) + 1, dtar->rna_path);
853                                         }
854                                 }
855                                 DRIVER_TARGETS_LOOPER_END;
856                         }
857                 }
858
859                 /* write F-Modifiers */
860                 write_fmodifiers(wd, &fcu->modifiers);
861         }
862 }
863
864 static void write_action(WriteData *wd, bAction *act)
865 {
866         if (act->id.us > 0 || wd->use_memfile) {
867                 writestruct(wd, ID_AC, bAction, 1, act);
868                 write_iddata(wd, &act->id);
869
870                 write_fcurves(wd, &act->curves);
871
872                 for (bActionGroup *grp = act->groups.first; grp; grp = grp->next) {
873                         writestruct(wd, DATA, bActionGroup, 1, grp);
874                 }
875
876                 for (TimeMarker *marker = act->markers.first; marker; marker = marker->next) {
877                         writestruct(wd, DATA, TimeMarker, 1, marker);
878                 }
879         }
880 }
881
882 static void write_keyingsets(WriteData *wd, ListBase *list)
883 {
884         KeyingSet *ks;
885         KS_Path *ksp;
886
887         for (ks = list->first; ks; ks = ks->next) {
888                 /* KeyingSet */
889                 writestruct(wd, DATA, KeyingSet, 1, ks);
890
891                 /* Paths */
892                 for (ksp = ks->paths.first; ksp; ksp = ksp->next) {
893                         /* Path */
894                         writestruct(wd, DATA, KS_Path, 1, ksp);
895
896                         if (ksp->rna_path) {
897                                 writedata(wd, DATA, strlen(ksp->rna_path) + 1, ksp->rna_path);
898                         }
899                 }
900         }
901 }
902
903 static void write_nlastrips(WriteData *wd, ListBase *strips)
904 {
905         NlaStrip *strip;
906
907         writelist(wd, DATA, NlaStrip, strips);
908         for (strip = strips->first; strip; strip = strip->next) {
909                 /* write the strip's F-Curves and modifiers */
910                 write_fcurves(wd, &strip->fcurves);
911                 write_fmodifiers(wd, &strip->modifiers);
912
913                 /* write the strip's children */
914                 write_nlastrips(wd, &strip->strips);
915         }
916 }
917
918 static void write_nladata(WriteData *wd, ListBase *nlabase)
919 {
920         NlaTrack *nlt;
921
922         /* write all the tracks */
923         for (nlt = nlabase->first; nlt; nlt = nlt->next) {
924                 /* write the track first */
925                 writestruct(wd, DATA, NlaTrack, 1, nlt);
926
927                 /* write the track's strips */
928                 write_nlastrips(wd, &nlt->strips);
929         }
930 }
931
932 static void write_animdata(WriteData *wd, AnimData *adt)
933 {
934         AnimOverride *aor;
935
936         /* firstly, just write the AnimData block */
937         writestruct(wd, DATA, AnimData, 1, adt);
938
939         /* write drivers */
940         write_fcurves(wd, &adt->drivers);
941
942         /* write overrides */
943         // FIXME: are these needed?
944         for (aor = adt->overrides.first; aor; aor = aor->next) {
945                 /* overrides consist of base data + rna_path */
946                 writestruct(wd, DATA, AnimOverride, 1, aor);
947                 writedata(wd, DATA, strlen(aor->rna_path) + 1, aor->rna_path);
948         }
949
950         // TODO write the remaps (if they are needed)
951
952         /* write NLA data */
953         write_nladata(wd, &adt->nla_tracks);
954 }
955
956 static void write_curvemapping_curves(WriteData *wd, CurveMapping *cumap)
957 {
958         for (int a = 0; a < CM_TOT; a++) {
959                 writestruct(wd, DATA, CurveMapPoint, cumap->cm[a].totpoint, cumap->cm[a].curve);
960         }
961 }
962
963 static void write_curvemapping(WriteData *wd, CurveMapping *cumap)
964 {
965         writestruct(wd, DATA, CurveMapping, 1, cumap);
966
967         write_curvemapping_curves(wd, cumap);
968 }
969
970 static void write_node_socket(WriteData *wd, bNodeTree *UNUSED(ntree), bNode *node, bNodeSocket *sock)
971 {
972 #ifdef USE_NODE_COMPAT_CUSTOMNODES
973         /* forward compatibility code, so older blenders still open (not for undo) */
974         if (wd->use_memfile == false) {
975                 sock->stack_type = 1;
976
977                 if (node->type == NODE_GROUP) {
978                         bNodeTree *ngroup = (bNodeTree *)node->id;
979                         if (ngroup) {
980                                 /* for node groups: look up the deprecated groupsock pointer */
981                                 sock->groupsock = ntreeFindSocketInterface(ngroup, sock->in_out, sock->identifier);
982                                 BLI_assert(sock->groupsock != NULL);
983
984                                 /* node group sockets now use the generic identifier string to verify group nodes,
985                                  * old blender uses the own_index.
986                                  */
987                                 sock->own_index = sock->groupsock->own_index;
988                         }
989                 }
990         }
991 #endif
992
993         /* actual socket writing */
994         writestruct(wd, DATA, bNodeSocket, 1, sock);
995
996         if (sock->prop) {
997                 IDP_WriteProperty(sock->prop, wd);
998         }
999
1000         if (sock->default_value) {
1001                 writedata(wd, DATA, MEM_allocN_len(sock->default_value), sock->default_value);
1002         }
1003 }
1004 static void write_node_socket_interface(WriteData *wd, bNodeTree *UNUSED(ntree), bNodeSocket *sock)
1005 {
1006 #ifdef USE_NODE_COMPAT_CUSTOMNODES
1007         /* forward compatibility code, so older blenders still open */
1008         sock->stack_type = 1;
1009
1010         /* Reconstruct the deprecated default_value structs in socket interface DNA. */
1011         if (sock->default_value == NULL && sock->typeinfo) {
1012                 node_socket_init_default_value(sock);
1013         }
1014 #endif
1015
1016         /* actual socket writing */
1017         writestruct(wd, DATA, bNodeSocket, 1, sock);
1018
1019         if (sock->prop) {
1020                 IDP_WriteProperty(sock->prop, wd);
1021         }
1022
1023         if (sock->default_value) {
1024                 writedata(wd, DATA, MEM_allocN_len(sock->default_value), sock->default_value);
1025         }
1026 }
1027 /* this is only direct data, tree itself should have been written */
1028 static void write_nodetree_nolib(WriteData *wd, bNodeTree *ntree)
1029 {
1030         bNode *node;
1031         bNodeSocket *sock;
1032         bNodeLink *link;
1033
1034         /* for link_list() speed, we write per list */
1035
1036         if (ntree->adt) {
1037                 write_animdata(wd, ntree->adt);
1038         }
1039
1040         for (node = ntree->nodes.first; node; node = node->next) {
1041                 writestruct(wd, DATA, bNode, 1, node);
1042
1043                 if (node->prop) {
1044                         IDP_WriteProperty(node->prop, wd);
1045                 }
1046
1047                 for (sock = node->inputs.first; sock; sock = sock->next) {
1048                         write_node_socket(wd, ntree, node, sock);
1049                 }
1050                 for (sock = node->outputs.first; sock; sock = sock->next) {
1051                         write_node_socket(wd, ntree, node, sock);
1052                 }
1053
1054                 for (link = node->internal_links.first; link; link = link->next) {
1055                         writestruct(wd, DATA, bNodeLink, 1, link);
1056                 }
1057
1058                 if (node->storage) {
1059                         /* could be handlerized at some point, now only 1 exception still */
1060                         if ((ntree->type == NTREE_SHADER) &&
1061                             ELEM(node->type, SH_NODE_CURVE_VEC, SH_NODE_CURVE_RGB))
1062                         {
1063                                 write_curvemapping(wd, node->storage);
1064                         }
1065                         else if (ntree->type == NTREE_SHADER &&
1066                                  (node->type == SH_NODE_SCRIPT))
1067                         {
1068                                 NodeShaderScript *nss = (NodeShaderScript *)node->storage;
1069                                 if (nss->bytecode) {
1070                                         writedata(wd, DATA, strlen(nss->bytecode) + 1, nss->bytecode);
1071                                 }
1072                                 writestruct_id(wd, DATA, node->typeinfo->storagename, 1, node->storage);
1073                         }
1074                         else if ((ntree->type == NTREE_COMPOSIT) &&
1075                                  ELEM(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB, CMP_NODE_HUECORRECT))
1076                         {
1077                                 write_curvemapping(wd, node->storage);
1078                         }
1079                         else if ((ntree->type == NTREE_TEXTURE) &&
1080                                  (node->type == TEX_NODE_CURVE_RGB || node->type == TEX_NODE_CURVE_TIME))
1081                         {
1082                                 write_curvemapping(wd, node->storage);
1083                         }
1084                         else if ((ntree->type == NTREE_COMPOSIT) &&
1085                                  (node->type == CMP_NODE_MOVIEDISTORTION))
1086                         {
1087                                 /* pass */
1088                         }
1089                         else if ((ntree->type == NTREE_COMPOSIT) && (node->type == CMP_NODE_GLARE)) {
1090                                 /* Simple forward compat for fix for T50736.
1091                                  * Not ideal (there is no ideal solution here), but should do for now. */
1092                                 NodeGlare *ndg = node->storage;
1093                                 /* Not in undo case. */
1094                                 if (wd->use_memfile == false) {
1095                                         switch (ndg->type) {
1096                                                 case 2:  /* Grrrr! magic numbers :( */
1097                                                         ndg->angle = ndg->streaks;
1098                                                         break;
1099                                                 case 0:
1100                                                         ndg->angle = ndg->star_45;
1101                                                         break;
1102                                                 default:
1103                                                         break;
1104                                         }
1105                                 }
1106                                 writestruct_id(wd, DATA, node->typeinfo->storagename, 1, node->storage);
1107                         }
1108                         else if ((ntree->type == NTREE_COMPOSIT) && (node->type == CMP_NODE_CRYPTOMATTE)) {
1109                                 NodeCryptomatte *nc = (NodeCryptomatte *)node->storage;
1110                                 if (nc->matte_id) {
1111                                         writedata(wd, DATA, strlen(nc->matte_id) + 1, nc->matte_id);
1112                                 }
1113                                 writestruct_id(wd, DATA, node->typeinfo->storagename, 1, node->storage);
1114                         }
1115                         else {
1116                                 writestruct_id(wd, DATA, node->typeinfo->storagename, 1, node->storage);
1117                         }
1118                 }
1119
1120                 if (node->type == CMP_NODE_OUTPUT_FILE) {
1121                         /* inputs have own storage data */
1122                         for (sock = node->inputs.first; sock; sock = sock->next) {
1123                                 writestruct(wd, DATA, NodeImageMultiFileSocket, 1, sock->storage);
1124                         }
1125                 }
1126                 if (ELEM(node->type, CMP_NODE_IMAGE, CMP_NODE_R_LAYERS)) {
1127                         /* write extra socket info */
1128                         for (sock = node->outputs.first; sock; sock = sock->next) {
1129                                 writestruct(wd, DATA, NodeImageLayer, 1, sock->storage);
1130                         }
1131                 }
1132         }
1133
1134         for (link = ntree->links.first; link; link = link->next) {
1135                 writestruct(wd, DATA, bNodeLink, 1, link);
1136         }
1137
1138         for (sock = ntree->inputs.first; sock; sock = sock->next) {
1139                 write_node_socket_interface(wd, ntree, sock);
1140         }
1141         for (sock = ntree->outputs.first; sock; sock = sock->next) {
1142                 write_node_socket_interface(wd, ntree, sock);
1143         }
1144 }
1145
1146 /**
1147  * Take care using 'use_active_win', since we wont want the currently active window
1148  * to change which scene renders (currently only used for undo).
1149  */
1150 static void current_screen_compat(
1151         Main *mainvar, bool use_active_win,
1152         bScreen **r_screen, Scene **r_scene, ViewLayer **r_view_layer)
1153 {
1154         wmWindowManager *wm;
1155         wmWindow *window = NULL;
1156
1157         /* find a global current screen in the first open window, to have
1158          * a reasonable default for reading in older versions */
1159         wm = mainvar->wm.first;
1160
1161         if (wm) {
1162                 if (use_active_win) {
1163                         /* write the active window into the file, needed for multi-window undo T43424 */
1164                         for (window = wm->windows.first; window; window = window->next) {
1165                                 if (window->active) {
1166                                         break;
1167                                 }
1168                         }
1169
1170                         /* fallback */
1171                         if (window == NULL) {
1172                                 window = wm->windows.first;
1173                         }
1174                 }
1175                 else {
1176                         window = wm->windows.first;
1177                 }
1178         }
1179
1180         *r_screen = (window) ? BKE_workspace_active_screen_get(window->workspace_hook) : NULL;
1181         *r_scene = (window) ? window->scene : NULL;
1182         *r_view_layer = (window && *r_scene) ? BKE_view_layer_find(*r_scene, window->view_layer_name) : NULL;
1183 }
1184
1185 typedef struct RenderInfo {
1186         int sfra;
1187         int efra;
1188         char scene_name[MAX_ID_NAME - 2];
1189 } RenderInfo;
1190
1191 /* was for historic render-deamon feature,
1192  * now write because it can be easily extracted without
1193  * reading the whole blend file */
1194 static void write_renderinfo(WriteData *wd, Main *mainvar)
1195 {
1196         bScreen *curscreen;
1197         Scene *sce, *curscene = NULL;
1198         ViewLayer *view_layer;
1199         RenderInfo data;
1200
1201         /* XXX in future, handle multiple windows with multiple screens? */
1202         current_screen_compat(mainvar, false, &curscreen, &curscene, &view_layer);
1203
1204         for (sce = mainvar->scene.first; sce; sce = sce->id.next) {
1205                 if (sce->id.lib == NULL && (sce == curscene || (sce->r.scemode & R_BG_RENDER))) {
1206                         data.sfra = sce->r.sfra;
1207                         data.efra = sce->r.efra;
1208                         memset(data.scene_name, 0, sizeof(data.scene_name));
1209
1210                         BLI_strncpy(data.scene_name, sce->id.name + 2, sizeof(data.scene_name));
1211
1212                         writedata(wd, REND, sizeof(data), &data);
1213                 }
1214         }
1215 }
1216
1217 static void write_keymapitem(WriteData *wd, const wmKeyMapItem *kmi)
1218 {
1219         writestruct(wd, DATA, wmKeyMapItem, 1, kmi);
1220         if (kmi->properties) {
1221                 IDP_WriteProperty(kmi->properties, wd);
1222         }
1223 }
1224
1225 static void write_userdef(WriteData *wd, const UserDef *userdef)
1226 {
1227         writestruct(wd, USER, UserDef, 1, userdef);
1228
1229         for (const bTheme *btheme = userdef->themes.first; btheme; btheme = btheme->next) {
1230                 writestruct(wd, DATA, bTheme, 1, btheme);
1231         }
1232
1233         for (const wmKeyMap *keymap = userdef->user_keymaps.first; keymap; keymap = keymap->next) {
1234                 writestruct(wd, DATA, wmKeyMap, 1, keymap);
1235
1236                 for (const wmKeyMapDiffItem *kmdi = keymap->diff_items.first; kmdi; kmdi = kmdi->next) {
1237                         writestruct(wd, DATA, wmKeyMapDiffItem, 1, kmdi);
1238                         if (kmdi->remove_item) {
1239                                 write_keymapitem(wd, kmdi->remove_item);
1240                         }
1241                         if (kmdi->add_item) {
1242                                 write_keymapitem(wd, kmdi->add_item);
1243                         }
1244                 }
1245
1246                 for (const wmKeyMapItem *kmi = keymap->items.first; kmi; kmi = kmi->next) {
1247                         write_keymapitem(wd, kmi);
1248                 }
1249         }
1250
1251         for (const wmKeyConfigPref *kpt = userdef->user_keyconfig_prefs.first; kpt; kpt = kpt->next) {
1252                 writestruct(wd, DATA, wmKeyConfigPref, 1, kpt);
1253                 if (kpt->prop) {
1254                         IDP_WriteProperty(kpt->prop, wd);
1255                 }
1256         }
1257
1258         for (const bUserMenu *um = userdef->user_menus.first; um; um = um->next) {
1259                 writestruct(wd, DATA, bUserMenu, 1, um);
1260                 for (const bUserMenuItem *umi = um->items.first; umi; umi = umi->next) {
1261                         if (umi->type == USER_MENU_TYPE_OPERATOR) {
1262                                 const bUserMenuItem_Op *umi_op = (const bUserMenuItem_Op *)umi;
1263                                 writestruct(wd, DATA, bUserMenuItem_Op, 1, umi_op);
1264                                 if (umi_op->prop) {
1265                                         IDP_WriteProperty(umi_op->prop, wd);
1266                                 }
1267                         }
1268                         else if (umi->type == USER_MENU_TYPE_MENU) {
1269                                 const bUserMenuItem_Menu *umi_mt = (const bUserMenuItem_Menu *)umi;
1270                                 writestruct(wd, DATA, bUserMenuItem_Menu, 1, umi_mt);
1271                         }
1272                         else if (umi->type == USER_MENU_TYPE_PROP) {
1273                                 const bUserMenuItem_Prop *umi_pr = (const bUserMenuItem_Prop *)umi;
1274                                 writestruct(wd, DATA, bUserMenuItem_Prop, 1, umi_pr);
1275                         }
1276                         else {
1277                                 writestruct(wd, DATA, bUserMenuItem, 1, umi);
1278                         }
1279                 }
1280         }
1281
1282         for (const bAddon *bext = userdef->addons.first; bext; bext = bext->next) {
1283                 writestruct(wd, DATA, bAddon, 1, bext);
1284                 if (bext->prop) {
1285                         IDP_WriteProperty(bext->prop, wd);
1286                 }
1287         }
1288
1289         for (const bPathCompare *path_cmp = userdef->autoexec_paths.first; path_cmp; path_cmp = path_cmp->next) {
1290                 writestruct(wd, DATA, bPathCompare, 1, path_cmp);
1291         }
1292
1293         for (const uiStyle *style = userdef->uistyles.first; style; style = style->next) {
1294                 writestruct(wd, DATA, uiStyle, 1, style);
1295         }
1296 }
1297
1298 static void write_boid_state(WriteData *wd, BoidState *state)
1299 {
1300         BoidRule *rule = state->rules.first;
1301
1302         writestruct(wd, DATA, BoidState, 1, state);
1303
1304         for (; rule; rule = rule->next) {
1305                 switch (rule->type) {
1306                         case eBoidRuleType_Goal:
1307                         case eBoidRuleType_Avoid:
1308                                 writestruct(wd, DATA, BoidRuleGoalAvoid, 1, rule);
1309                                 break;
1310                         case eBoidRuleType_AvoidCollision:
1311                                 writestruct(wd, DATA, BoidRuleAvoidCollision, 1, rule);
1312                                 break;
1313                         case eBoidRuleType_FollowLeader:
1314                                 writestruct(wd, DATA, BoidRuleFollowLeader, 1, rule);
1315                                 break;
1316                         case eBoidRuleType_AverageSpeed:
1317                                 writestruct(wd, DATA, BoidRuleAverageSpeed, 1, rule);
1318                                 break;
1319                         case eBoidRuleType_Fight:
1320                                 writestruct(wd, DATA, BoidRuleFight, 1, rule);
1321                                 break;
1322                         default:
1323                                 writestruct(wd, DATA, BoidRule, 1, rule);
1324                                 break;
1325                 }
1326         }
1327 #if 0
1328         BoidCondition *cond = state->conditions.first;
1329         for (; cond; cond = cond->next) {
1330                 writestruct(wd, DATA, BoidCondition, 1, cond);
1331         }
1332 #endif
1333 }
1334
1335 /* update this also to readfile.c */
1336 static const char *ptcache_data_struct[] = {
1337         "", // BPHYS_DATA_INDEX
1338         "", // BPHYS_DATA_LOCATION
1339         "", // BPHYS_DATA_VELOCITY
1340         "", // BPHYS_DATA_ROTATION
1341         "", // BPHYS_DATA_AVELOCITY / BPHYS_DATA_XCONST */
1342         "", // BPHYS_DATA_SIZE:
1343         "", // BPHYS_DATA_TIMES:
1344         "BoidData" // case BPHYS_DATA_BOIDS:
1345 };
1346 static const char *ptcache_extra_struct[] = {
1347         "",
1348         "ParticleSpring"
1349 };
1350 static void write_pointcaches(WriteData *wd, ListBase *ptcaches)
1351 {
1352         PointCache *cache = ptcaches->first;
1353         int i;
1354
1355         for (; cache; cache = cache->next) {
1356                 writestruct(wd, DATA, PointCache, 1, cache);
1357
1358                 if ((cache->flag & PTCACHE_DISK_CACHE) == 0) {
1359                         PTCacheMem *pm = cache->mem_cache.first;
1360
1361                         for (; pm; pm = pm->next) {
1362                                 PTCacheExtra *extra = pm->extradata.first;
1363
1364                                 writestruct(wd, DATA, PTCacheMem, 1, pm);
1365
1366                                 for (i = 0; i < BPHYS_TOT_DATA; i++) {
1367                                         if (pm->data[i] && pm->data_types & (1 << i)) {
1368                                                 if (ptcache_data_struct[i][0] == '\0') {
1369                                                         writedata(wd, DATA, MEM_allocN_len(pm->data[i]), pm->data[i]);
1370                                                 }
1371                                                 else {
1372                                                         writestruct_id(wd, DATA, ptcache_data_struct[i], pm->totpoint, pm->data[i]);
1373                                                 }
1374                                         }
1375                                 }
1376
1377                                 for (; extra; extra = extra->next) {
1378                                         if (ptcache_extra_struct[extra->type][0] == '\0') {
1379                                                 continue;
1380                                         }
1381                                         writestruct(wd, DATA, PTCacheExtra, 1, extra);
1382                                         writestruct_id(wd, DATA, ptcache_extra_struct[extra->type], extra->totdata, extra->data);
1383                                 }
1384                         }
1385                 }
1386         }
1387 }
1388
1389 static void write_particlesettings(WriteData *wd, ParticleSettings *part)
1390 {
1391         if (part->id.us > 0 || wd->use_memfile) {
1392                 /* write LibData */
1393                 writestruct(wd, ID_PA, ParticleSettings, 1, part);
1394                 write_iddata(wd, &part->id);
1395
1396                 if (part->adt) {
1397                         write_animdata(wd, part->adt);
1398                 }
1399                 writestruct(wd, DATA, PartDeflect, 1, part->pd);
1400                 writestruct(wd, DATA, PartDeflect, 1, part->pd2);
1401                 writestruct(wd, DATA, EffectorWeights, 1, part->effector_weights);
1402
1403                 if (part->clumpcurve) {
1404                         write_curvemapping(wd, part->clumpcurve);
1405                 }
1406                 if (part->roughcurve) {
1407                         write_curvemapping(wd, part->roughcurve);
1408                 }
1409                 if (part->twistcurve) {
1410                         write_curvemapping(wd, part->twistcurve);
1411                 }
1412
1413                 for (ParticleDupliWeight *dw = part->dupliweights.first; dw; dw = dw->next) {
1414                         /* update indices, but only if dw->ob is set (can be NULL after loading e.g.) */
1415                         if (dw->ob != NULL) {
1416                                 dw->index = 0;
1417                                 if (part->dup_group) { /* can be NULL if lining fails or set to None */
1418                                         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(part->dup_group, object)
1419                                         {
1420                                                 if (object != dw->ob) {
1421                                                         dw->index++;
1422                                                 }
1423                                         }
1424                                         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1425                                 }
1426                         }
1427                         writestruct(wd, DATA, ParticleDupliWeight, 1, dw);
1428                 }
1429
1430                 if (part->boids && part->phystype == PART_PHYS_BOIDS) {
1431                         writestruct(wd, DATA, BoidSettings, 1, part->boids);
1432
1433                         for (BoidState *state = part->boids->states.first; state; state = state->next) {
1434                                 write_boid_state(wd, state);
1435                         }
1436                 }
1437                 if (part->fluid && part->phystype == PART_PHYS_FLUID) {
1438                         writestruct(wd, DATA, SPHFluidSettings, 1, part->fluid);
1439                 }
1440
1441                 for (int a = 0; a < MAX_MTEX; a++) {
1442                         if (part->mtex[a]) {
1443                                 writestruct(wd, DATA, MTex, 1, part->mtex[a]);
1444                         }
1445                 }
1446         }
1447 }
1448
1449 static void write_particlesystems(WriteData *wd, ListBase *particles)
1450 {
1451         ParticleSystem *psys = particles->first;
1452         ParticleTarget *pt;
1453         int a;
1454
1455         for (; psys; psys = psys->next) {
1456                 writestruct(wd, DATA, ParticleSystem, 1, psys);
1457
1458                 if (psys->particles) {
1459                         writestruct(wd, DATA, ParticleData, psys->totpart, psys->particles);
1460
1461                         if (psys->particles->hair) {
1462                                 ParticleData *pa = psys->particles;
1463
1464                                 for (a = 0; a < psys->totpart; a++, pa++) {
1465                                         writestruct(wd, DATA, HairKey, pa->totkey, pa->hair);
1466                                 }
1467                         }
1468
1469                         if (psys->particles->boid &&
1470                             (psys->part->phystype == PART_PHYS_BOIDS))
1471                         {
1472                                 writestruct(wd, DATA, BoidParticle, psys->totpart, psys->particles->boid);
1473                         }
1474
1475                         if (psys->part->fluid &&
1476                             (psys->part->phystype == PART_PHYS_FLUID) &&
1477                             (psys->part->fluid->flag & SPH_VISCOELASTIC_SPRINGS))
1478                         {
1479                                 writestruct(wd, DATA, ParticleSpring, psys->tot_fluidsprings, psys->fluid_springs);
1480                         }
1481                 }
1482                 pt = psys->targets.first;
1483                 for (; pt; pt = pt->next) {
1484                         writestruct(wd, DATA, ParticleTarget, 1, pt);
1485                 }
1486
1487                 if (psys->child) {
1488                         writestruct(wd, DATA, ChildParticle, psys->totchild, psys->child);
1489                 }
1490
1491                 if (psys->clmd) {
1492                         writestruct(wd, DATA, ClothModifierData, 1, psys->clmd);
1493                         writestruct(wd, DATA, ClothSimSettings, 1, psys->clmd->sim_parms);
1494                         writestruct(wd, DATA, ClothCollSettings, 1, psys->clmd->coll_parms);
1495                 }
1496
1497                 write_pointcaches(wd, &psys->ptcaches);
1498         }
1499 }
1500
1501 static void write_motionpath(WriteData *wd, bMotionPath *mpath)
1502 {
1503         /* sanity checks */
1504         if (mpath == NULL) {
1505                 return;
1506         }
1507
1508         /* firstly, just write the motionpath struct */
1509         writestruct(wd, DATA, bMotionPath, 1, mpath);
1510
1511         /* now write the array of data */
1512         writestruct(wd, DATA, bMotionPathVert, mpath->length, mpath->points);
1513 }
1514
1515 static void write_constraints(WriteData *wd, ListBase *conlist)
1516 {
1517         bConstraint *con;
1518
1519         for (con = conlist->first; con; con = con->next) {
1520                 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
1521
1522                 /* Write the specific data */
1523                 if (cti && con->data) {
1524                         /* firstly, just write the plain con->data struct */
1525                         writestruct_id(wd, DATA, cti->structName, 1, con->data);
1526
1527                         /* do any constraint specific stuff */
1528                         switch (con->type) {
1529                                 case CONSTRAINT_TYPE_PYTHON:
1530                                 {
1531                                         bPythonConstraint *data = con->data;
1532                                         bConstraintTarget *ct;
1533
1534                                         /* write targets */
1535                                         for (ct = data->targets.first; ct; ct = ct->next) {
1536                                                 writestruct(wd, DATA, bConstraintTarget, 1, ct);
1537                                         }
1538
1539                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1540                                          * of library blocks that implement this.*/
1541                                         IDP_WriteProperty(data->prop, wd);
1542
1543                                         break;
1544                                 }
1545                                 case CONSTRAINT_TYPE_ARMATURE:
1546                                 {
1547                                         bArmatureConstraint *data = con->data;
1548                                         bConstraintTarget *ct;
1549
1550                                         /* write targets */
1551                                         for (ct = data->targets.first; ct; ct = ct->next) {
1552                                                 writestruct(wd, DATA, bConstraintTarget, 1, ct);
1553                                         }
1554
1555                                         break;
1556                                 }
1557                                 case CONSTRAINT_TYPE_SPLINEIK:
1558                                 {
1559                                         bSplineIKConstraint *data = con->data;
1560
1561                                         /* write points array */
1562                                         writedata(wd, DATA, sizeof(float) * (data->numpoints), data->points);
1563
1564                                         break;
1565                                 }
1566                         }
1567                 }
1568
1569                 /* Write the constraint */
1570                 writestruct(wd, DATA, bConstraint, 1, con);
1571         }
1572 }
1573
1574 static void write_pose(WriteData *wd, bPose *pose)
1575 {
1576         bPoseChannel *chan;
1577         bActionGroup *grp;
1578
1579         /* Write each channel */
1580         if (pose == NULL) {
1581                 return;
1582         }
1583
1584         /* Write channels */
1585         for (chan = pose->chanbase.first; chan; chan = chan->next) {
1586                 /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1587                  * of library blocks that implement this.*/
1588                 if (chan->prop) {
1589                         IDP_WriteProperty(chan->prop, wd);
1590                 }
1591
1592                 write_constraints(wd, &chan->constraints);
1593
1594                 write_motionpath(wd, chan->mpath);
1595
1596                 /* prevent crashes with autosave,
1597                  * when a bone duplicated in editmode has not yet been assigned to its posechannel */
1598                 if (chan->bone) {
1599                         /* gets restored on read, for library armatures */
1600                         chan->selectflag = chan->bone->flag & BONE_SELECTED;
1601                 }
1602
1603                 writestruct(wd, DATA, bPoseChannel, 1, chan);
1604         }
1605
1606         /* Write groups */
1607         for (grp = pose->agroups.first; grp; grp = grp->next) {
1608                 writestruct(wd, DATA, bActionGroup, 1, grp);
1609         }
1610
1611         /* write IK param */
1612         if (pose->ikparam) {
1613                 const char *structname = BKE_pose_ikparam_get_name(pose);
1614                 if (structname) {
1615                         writestruct_id(wd, DATA, structname, 1, pose->ikparam);
1616                 }
1617         }
1618
1619         /* Write this pose */
1620         writestruct(wd, DATA, bPose, 1, pose);
1621
1622 }
1623
1624 static void write_defgroups(WriteData *wd, ListBase *defbase)
1625 {
1626         for (bDeformGroup *defgroup = defbase->first; defgroup; defgroup = defgroup->next) {
1627                 writestruct(wd, DATA, bDeformGroup, 1, defgroup);
1628         }
1629 }
1630
1631 static void write_fmaps(WriteData *wd, ListBase *fbase)
1632 {
1633         for (bFaceMap *fmap = fbase->first; fmap; fmap = fmap->next) {
1634                 writestruct(wd, DATA, bFaceMap, 1, fmap);
1635         }
1636 }
1637
1638 static void write_modifiers(WriteData *wd, ListBase *modbase)
1639 {
1640         ModifierData *md;
1641
1642         if (modbase == NULL) {
1643                 return;
1644         }
1645
1646         for (md = modbase->first; md; md = md->next) {
1647                 const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1648                 if (mti == NULL) {
1649                         return;
1650                 }
1651
1652                 writestruct_id(wd, DATA, mti->structName, 1, md);
1653
1654                 if (md->type == eModifierType_Hook) {
1655                         HookModifierData *hmd = (HookModifierData *)md;
1656
1657                         if (hmd->curfalloff) {
1658                                 write_curvemapping(wd, hmd->curfalloff);
1659                         }
1660
1661                         writedata(wd, DATA, sizeof(int) * hmd->totindex, hmd->indexar);
1662                 }
1663                 else if (md->type == eModifierType_Cloth) {
1664                         ClothModifierData *clmd = (ClothModifierData *)md;
1665
1666                         writestruct(wd, DATA, ClothSimSettings, 1, clmd->sim_parms);
1667                         writestruct(wd, DATA, ClothCollSettings, 1, clmd->coll_parms);
1668                         writestruct(wd, DATA, EffectorWeights, 1, clmd->sim_parms->effector_weights);
1669                         write_pointcaches(wd, &clmd->ptcaches);
1670                 }
1671                 else if (md->type == eModifierType_Smoke) {
1672                         SmokeModifierData *smd = (SmokeModifierData *)md;
1673
1674                         if (smd->type & MOD_SMOKE_TYPE_DOMAIN) {
1675                                 writestruct(wd, DATA, SmokeDomainSettings, 1, smd->domain);
1676
1677                                 if (smd->domain) {
1678                                         write_pointcaches(wd, &(smd->domain->ptcaches[0]));
1679
1680                                         /* create fake pointcache so that old blender versions can read it */
1681                                         smd->domain->point_cache[1] = BKE_ptcache_add(&smd->domain->ptcaches[1]);
1682                                         smd->domain->point_cache[1]->flag |= PTCACHE_DISK_CACHE | PTCACHE_FAKE_SMOKE;
1683                                         smd->domain->point_cache[1]->step = 1;
1684
1685                                         write_pointcaches(wd, &(smd->domain->ptcaches[1]));
1686
1687                                         if (smd->domain->coba) {
1688                                                 writestruct(wd, DATA, ColorBand, 1, smd->domain->coba);
1689                                         }
1690
1691
1692                                         /* cleanup the fake pointcache */
1693                                         BKE_ptcache_free_list(&smd->domain->ptcaches[1]);
1694                                         smd->domain->point_cache[1] = NULL;
1695
1696                                         writestruct(wd, DATA, EffectorWeights, 1, smd->domain->effector_weights);
1697                                 }
1698                         }
1699                         else if (smd->type & MOD_SMOKE_TYPE_FLOW) {
1700                                 writestruct(wd, DATA, SmokeFlowSettings, 1, smd->flow);
1701                         }
1702                         else if (smd->type & MOD_SMOKE_TYPE_COLL) {
1703                                 writestruct(wd, DATA, SmokeCollSettings, 1, smd->coll);
1704                         }
1705                 }
1706                 else if (md->type == eModifierType_Fluidsim) {
1707                         FluidsimModifierData *fluidmd = (FluidsimModifierData *)md;
1708
1709                         writestruct(wd, DATA, FluidsimSettings, 1, fluidmd->fss);
1710                 }
1711                 else if (md->type == eModifierType_DynamicPaint) {
1712                         DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md;
1713
1714                         if (pmd->canvas) {
1715                                 DynamicPaintSurface *surface;
1716                                 writestruct(wd, DATA, DynamicPaintCanvasSettings, 1, pmd->canvas);
1717
1718                                 /* write surfaces */
1719                                 for (surface = pmd->canvas->surfaces.first; surface; surface = surface->next) {
1720                                         writestruct(wd, DATA, DynamicPaintSurface, 1, surface);
1721                                 }
1722                                 /* write caches and effector weights */
1723                                 for (surface = pmd->canvas->surfaces.first; surface; surface = surface->next) {
1724                                         write_pointcaches(wd, &(surface->ptcaches));
1725
1726                                         writestruct(wd, DATA, EffectorWeights, 1, surface->effector_weights);
1727                                 }
1728                         }
1729                         if (pmd->brush) {
1730                                 writestruct(wd, DATA, DynamicPaintBrushSettings, 1, pmd->brush);
1731                                 writestruct(wd, DATA, ColorBand, 1, pmd->brush->paint_ramp);
1732                                 writestruct(wd, DATA, ColorBand, 1, pmd->brush->vel_ramp);
1733                         }
1734                 }
1735                 else if (md->type == eModifierType_Collision) {
1736
1737 #if 0
1738                         CollisionModifierData *collmd = (CollisionModifierData *)md;
1739                         // TODO: CollisionModifier should use pointcache
1740                         // + have proper reset events before enabling this
1741                         writestruct(wd, DATA, MVert, collmd->numverts, collmd->x);
1742                         writestruct(wd, DATA, MVert, collmd->numverts, collmd->xnew);
1743                         writestruct(wd, DATA, MFace, collmd->numfaces, collmd->mfaces);
1744 #endif
1745                 }
1746                 else if (md->type == eModifierType_MeshDeform) {
1747                         MeshDeformModifierData *mmd = (MeshDeformModifierData *)md;
1748                         int size = mmd->dyngridsize;
1749
1750                         writestruct(wd, DATA, MDefInfluence, mmd->totinfluence, mmd->bindinfluences);
1751                         writedata(wd, DATA, sizeof(int) * (mmd->totvert + 1), mmd->bindoffsets);
1752                         writedata(wd, DATA, sizeof(float) * 3 * mmd->totcagevert,
1753                                   mmd->bindcagecos);
1754                         writestruct(wd, DATA, MDefCell, size * size * size, mmd->dyngrid);
1755                         writestruct(wd, DATA, MDefInfluence, mmd->totinfluence, mmd->dyninfluences);
1756                         writedata(wd, DATA, sizeof(int) * mmd->totvert, mmd->dynverts);
1757                 }
1758                 else if (md->type == eModifierType_Warp) {
1759                         WarpModifierData *tmd = (WarpModifierData *)md;
1760                         if (tmd->curfalloff) {
1761                                 write_curvemapping(wd, tmd->curfalloff);
1762                         }
1763                 }
1764                 else if (md->type == eModifierType_WeightVGEdit) {
1765                         WeightVGEditModifierData *wmd = (WeightVGEditModifierData *)md;
1766
1767                         if (wmd->cmap_curve) {
1768                                 write_curvemapping(wd, wmd->cmap_curve);
1769                         }
1770                 }
1771                 else if (md->type == eModifierType_LaplacianDeform) {
1772                         LaplacianDeformModifierData *lmd = (LaplacianDeformModifierData *)md;
1773
1774                         writedata(wd, DATA, sizeof(float) * lmd->total_verts * 3, lmd->vertexco);
1775                 }
1776                 else if (md->type == eModifierType_CorrectiveSmooth) {
1777                         CorrectiveSmoothModifierData *csmd = (CorrectiveSmoothModifierData *)md;
1778
1779                         if (csmd->bind_coords) {
1780                                 writedata(wd, DATA, sizeof(float[3]) * csmd->bind_coords_num, csmd->bind_coords);
1781                         }
1782                 }
1783                 else if (md->type == eModifierType_SurfaceDeform) {
1784                         SurfaceDeformModifierData *smd = (SurfaceDeformModifierData *)md;
1785
1786                         writestruct(wd, DATA, SDefVert, smd->numverts, smd->verts);
1787
1788                         if (smd->verts) {
1789                                 for (int i = 0; i < smd->numverts; i++) {
1790                                         writestruct(wd, DATA, SDefBind, smd->verts[i].numbinds, smd->verts[i].binds);
1791
1792                                         if (smd->verts[i].binds) {
1793                                                 for (int j = 0; j < smd->verts[i].numbinds; j++) {
1794                                                         writedata(wd, DATA, sizeof(int) * smd->verts[i].binds[j].numverts, smd->verts[i].binds[j].vert_inds);
1795
1796                                                         if (smd->verts[i].binds[j].mode == MOD_SDEF_MODE_CENTROID ||
1797                                                             smd->verts[i].binds[j].mode == MOD_SDEF_MODE_LOOPTRI)
1798                                                         {
1799                                                                 writedata(wd, DATA, sizeof(float) * 3, smd->verts[i].binds[j].vert_weights);
1800                                                         }
1801                                                         else {
1802                                                                 writedata(wd, DATA, sizeof(float) * smd->verts[i].binds[j].numverts, smd->verts[i].binds[j].vert_weights);
1803                                                         }
1804                                                 }
1805                                         }
1806                                 }
1807                         }
1808                 }
1809         }
1810 }
1811
1812 static void write_gpencil_modifiers(WriteData *wd, ListBase *modbase)
1813 {
1814         GpencilModifierData *md;
1815
1816         if (modbase == NULL) {
1817                 return;
1818         }
1819
1820         for (md = modbase->first; md; md = md->next) {
1821                 const GpencilModifierTypeInfo *mti = BKE_gpencil_modifierType_getInfo(md->type);
1822                 if (mti == NULL) {
1823                         return;
1824                 }
1825
1826                 writestruct_id(wd, DATA, mti->struct_name, 1, md);
1827
1828                 if (md->type == eGpencilModifierType_Thick) {
1829                         ThickGpencilModifierData *gpmd = (ThickGpencilModifierData *)md;
1830
1831                         if (gpmd->curve_thickness) {
1832                                 write_curvemapping(wd, gpmd->curve_thickness);
1833                         }
1834                 }
1835                 else if (md->type == eGpencilModifierType_Hook) {
1836                         HookGpencilModifierData *gpmd = (HookGpencilModifierData *)md;
1837
1838                         if (gpmd->curfalloff) {
1839                                 write_curvemapping(wd, gpmd->curfalloff);
1840                         }
1841                 }
1842         }
1843 }
1844
1845 static void write_shaderfxs(WriteData *wd, ListBase *fxbase)
1846 {
1847         ShaderFxData *fx;
1848
1849         if (fxbase == NULL) {
1850                 return;
1851         }
1852
1853         for (fx = fxbase->first; fx; fx = fx->next) {
1854                 const ShaderFxTypeInfo *fxi = BKE_shaderfxType_getInfo(fx->type);
1855                 if (fxi == NULL) {
1856                         return;
1857                 }
1858
1859                 writestruct_id(wd, DATA, fxi->struct_name, 1, fx);
1860         }
1861 }
1862
1863 static void write_object(WriteData *wd, Object *ob)
1864 {
1865         if (ob->id.us > 0 || wd->use_memfile) {
1866                 /* write LibData */
1867                 writestruct(wd, ID_OB, Object, 1, ob);
1868                 write_iddata(wd, &ob->id);
1869
1870                 if (ob->adt) {
1871                         write_animdata(wd, ob->adt);
1872                 }
1873
1874                 /* direct data */
1875                 writedata(wd, DATA, sizeof(void *) * ob->totcol, ob->mat);
1876                 writedata(wd, DATA, sizeof(char) * ob->totcol, ob->matbits);
1877                 /* write_effects(wd, &ob->effect); */ /* not used anymore */
1878
1879                 if (ob->type == OB_ARMATURE) {
1880                         bArmature *arm = ob->data;
1881                         if (arm && ob->pose && arm->act_bone) {
1882                                 BLI_strncpy(ob->pose->proxy_act_bone, arm->act_bone->name, sizeof(ob->pose->proxy_act_bone));
1883                         }
1884                 }
1885
1886                 write_pose(wd, ob->pose);
1887                 write_defgroups(wd, &ob->defbase);
1888                 write_fmaps(wd, &ob->fmaps);
1889                 write_constraints(wd, &ob->constraints);
1890                 write_motionpath(wd, ob->mpath);
1891
1892                 writestruct(wd, DATA, PartDeflect, 1, ob->pd);
1893                 if (ob->soft) {
1894                         /* Set deprecated pointers to prevent crashes of older Blenders */
1895                         ob->soft->pointcache = ob->soft->shared->pointcache;
1896                         ob->soft->ptcaches = ob->soft->shared->ptcaches;
1897                         writestruct(wd, DATA, SoftBody, 1, ob->soft);
1898                         writestruct(wd, DATA, SoftBody_Shared, 1, ob->soft->shared);
1899                         write_pointcaches(wd, &(ob->soft->shared->ptcaches));
1900                         writestruct(wd, DATA, EffectorWeights, 1, ob->soft->effector_weights);
1901                 }
1902
1903                 if (ob->rigidbody_object) {
1904                         /* TODO: if any extra data is added to handle duplis, will need separate function then */
1905                         writestruct(wd, DATA, RigidBodyOb, 1, ob->rigidbody_object);
1906                 }
1907                 if (ob->rigidbody_constraint) {
1908                         writestruct(wd, DATA, RigidBodyCon, 1, ob->rigidbody_constraint);
1909                 }
1910
1911                 if (ob->type == OB_EMPTY && ob->empty_drawtype == OB_EMPTY_IMAGE) {
1912                         writestruct(wd, DATA, ImageUser, 1, ob->iuser);
1913                 }
1914
1915                 write_particlesystems(wd, &ob->particlesystem);
1916                 write_modifiers(wd, &ob->modifiers);
1917                 write_gpencil_modifiers(wd, &ob->greasepencil_modifiers);
1918                 write_shaderfxs(wd, &ob->shader_fx);
1919
1920                 writelist(wd, DATA, LinkData, &ob->pc_ids);
1921                 writelist(wd, DATA, LodLevel, &ob->lodlevels);
1922
1923                 write_previews(wd, ob->preview);
1924         }
1925 }
1926
1927
1928 static void write_vfont(WriteData *wd, VFont *vf)
1929 {
1930         if (vf->id.us > 0 || wd->use_memfile) {
1931                 /* write LibData */
1932                 writestruct(wd, ID_VF, VFont, 1, vf);
1933                 write_iddata(wd, &vf->id);
1934
1935                 /* direct data */
1936                 if (vf->packedfile) {
1937                         PackedFile *pf = vf->packedfile;
1938                         writestruct(wd, DATA, PackedFile, 1, pf);
1939                         writedata(wd, DATA, pf->size, pf->data);
1940                 }
1941         }
1942 }
1943
1944
1945 static void write_key(WriteData *wd, Key *key)
1946 {
1947         if (key->id.us > 0 || wd->use_memfile) {
1948                 /* write LibData */
1949                 writestruct(wd, ID_KE, Key, 1, key);
1950                 write_iddata(wd, &key->id);
1951
1952                 if (key->adt) {
1953                         write_animdata(wd, key->adt);
1954                 }
1955
1956                 /* direct data */
1957                 for (KeyBlock *kb = key->block.first; kb; kb = kb->next) {
1958                         writestruct(wd, DATA, KeyBlock, 1, kb);
1959                         if (kb->data) {
1960                                 writedata(wd, DATA, kb->totelem * key->elemsize, kb->data);
1961                         }
1962                 }
1963         }
1964 }
1965
1966 static void write_camera(WriteData *wd, Camera *cam)
1967 {
1968         if (cam->id.us > 0 || wd->use_memfile) {
1969                 /* write LibData */
1970                 writestruct(wd, ID_CA, Camera, 1, cam);
1971                 write_iddata(wd, &cam->id);
1972
1973                 if (cam->adt) {
1974                         write_animdata(wd, cam->adt);
1975                 }
1976
1977                 for (CameraBGImage *bgpic = cam->bg_images.first; bgpic; bgpic = bgpic->next) {
1978                         writestruct(wd, DATA, CameraBGImage, 1, bgpic);
1979                 }
1980         }
1981 }
1982
1983 static void write_mball(WriteData *wd, MetaBall *mb)
1984 {
1985         if (mb->id.us > 0 || wd->use_memfile) {
1986                 /* write LibData */
1987                 writestruct(wd, ID_MB, MetaBall, 1, mb);
1988                 write_iddata(wd, &mb->id);
1989
1990                 /* direct data */
1991                 writedata(wd, DATA, sizeof(void *) * mb->totcol, mb->mat);
1992                 if (mb->adt) {
1993                         write_animdata(wd, mb->adt);
1994                 }
1995
1996                 for (MetaElem *ml = mb->elems.first; ml; ml = ml->next) {
1997                         writestruct(wd, DATA, MetaElem, 1, ml);
1998                 }
1999         }
2000 }
2001
2002 static void write_curve(WriteData *wd, Curve *cu)
2003 {
2004         if (cu->id.us > 0 || wd->use_memfile) {
2005                 /* write LibData */
2006                 writestruct(wd, ID_CU, Curve, 1, cu);
2007                 write_iddata(wd, &cu->id);
2008
2009                 /* direct data */
2010                 writedata(wd, DATA, sizeof(void *) * cu->totcol, cu->mat);
2011                 if (cu->adt) {
2012                         write_animdata(wd, cu->adt);
2013                 }
2014
2015                 if (cu->vfont) {
2016                         writedata(wd, DATA, cu->len + 1, cu->str);
2017                         writestruct(wd, DATA, CharInfo, cu->len_wchar + 1, cu->strinfo);
2018                         writestruct(wd, DATA, TextBox, cu->totbox, cu->tb);
2019                 }
2020                 else {
2021                         /* is also the order of reading */
2022                         for (Nurb *nu = cu->nurb.first; nu; nu = nu->next) {
2023                                 writestruct(wd, DATA, Nurb, 1, nu);
2024                         }
2025                         for (Nurb *nu = cu->nurb.first; nu; nu = nu->next) {
2026                                 if (nu->type == CU_BEZIER) {
2027                                         writestruct(wd, DATA, BezTriple, nu->pntsu, nu->bezt);
2028                                 }
2029                                 else {
2030                                         writestruct(wd, DATA, BPoint, nu->pntsu * nu->pntsv, nu->bp);
2031                                         if (nu->knotsu) {
2032                                                 writedata(wd, DATA, KNOTSU(nu) * sizeof(float), nu->knotsu);
2033                                         }
2034                                         if (nu->knotsv) {
2035                                                 writedata(wd, DATA, KNOTSV(nu) * sizeof(float), nu->knotsv);
2036                                         }
2037                                 }
2038                         }
2039                 }
2040         }
2041 }
2042
2043 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
2044 {
2045         if (dvlist) {
2046
2047                 /* Write the dvert list */
2048                 writestruct(wd, DATA, MDeformVert, count, dvlist);
2049
2050                 /* Write deformation data for each dvert */
2051                 for (int i = 0; i < count; i++) {
2052                         if (dvlist[i].dw) {
2053                                 writestruct(wd, DATA, MDeformWeight, dvlist[i].totweight, dvlist[i].dw);
2054                         }
2055                 }
2056         }
2057 }
2058
2059 static void write_mdisps(WriteData *wd, int count, MDisps *mdlist, int external)
2060 {
2061         if (mdlist) {
2062                 int i;
2063
2064                 writestruct(wd, DATA, MDisps, count, mdlist);
2065                 for (i = 0; i < count; ++i) {
2066                         MDisps *md = &mdlist[i];
2067                         if (md->disps) {
2068                                 if (!external) {
2069                                         writedata(wd, DATA, sizeof(float) * 3 * md->totdisp, md->disps);
2070                                 }
2071                         }
2072
2073                         if (md->hidden) {
2074                                 writedata(wd, DATA, BLI_BITMAP_SIZE(md->totdisp), md->hidden);
2075                         }
2076                 }
2077         }
2078 }
2079
2080 static void write_grid_paint_mask(WriteData *wd, int count, GridPaintMask *grid_paint_mask)
2081 {
2082         if (grid_paint_mask) {
2083                 int i;
2084
2085                 writestruct(wd, DATA, GridPaintMask, count, grid_paint_mask);
2086                 for (i = 0; i < count; ++i) {
2087                         GridPaintMask *gpm = &grid_paint_mask[i];
2088                         if (gpm->data) {
2089                                 const int gridsize = BKE_ccg_gridsize(gpm->level);
2090                                 writedata(wd, DATA,
2091                                           sizeof(*gpm->data) * gridsize * gridsize,
2092                                           gpm->data);
2093                         }
2094                 }
2095         }
2096 }
2097
2098 static void write_customdata(
2099         WriteData *wd, ID *id, int count, CustomData *data, CustomDataLayer *layers,
2100         int partial_type, int partial_count)
2101 {
2102         int i;
2103
2104         /* write external customdata (not for undo) */
2105         if (data->external && (wd->use_memfile == false)) {
2106                 CustomData_external_write(data, id, CD_MASK_MESH, count, 0);
2107         }
2108
2109         writestruct_at_address(wd, DATA, CustomDataLayer, data->totlayer, data->layers, layers);
2110
2111         for (i = 0; i < data->totlayer; i++) {
2112                 CustomDataLayer *layer = &layers[i];
2113                 const char *structname;
2114                 int structnum, datasize;
2115
2116                 if (layer->type == CD_MDEFORMVERT) {
2117                         /* layer types that allocate own memory need special handling */
2118                         write_dverts(wd, count, layer->data);
2119                 }
2120                 else if (layer->type == CD_MDISPS) {
2121                         write_mdisps(wd, count, layer->data, layer->flag & CD_FLAG_EXTERNAL);
2122                 }
2123                 else if (layer->type == CD_PAINT_MASK) {
2124                         const float *layer_data = layer->data;
2125                         writedata(wd, DATA, sizeof(*layer_data) * count, layer_data);
2126                 }
2127                 else if (layer->type == CD_GRID_PAINT_MASK) {
2128                         write_grid_paint_mask(wd, count, layer->data);
2129                 }
2130                 else if (layer->type == CD_FACEMAP) {
2131                         const int *layer_data = layer->data;
2132                         writedata(wd, DATA, sizeof(*layer_data) * count, layer_data);
2133                 }
2134                 else {
2135                         CustomData_file_write_info(layer->type, &structname, &structnum);
2136                         if (structnum) {
2137                                 /* when using partial visibility, the MEdge and MFace layers
2138                                  * are smaller than the original, so their type and count is
2139                                  * passed to make this work */
2140                                 if (layer->type != partial_type) {
2141                                         datasize = structnum * count;
2142                                 }
2143                                 else {
2144                                         datasize = structnum * partial_count;
2145                                 }
2146
2147                                 writestruct_id(wd, DATA, structname, datasize, layer->data);
2148                         }
2149                         else {
2150                                 printf("%s error: layer '%s':%d - can't be written to file\n",
2151                                        __func__, structname, layer->type);
2152                         }
2153                 }
2154         }
2155
2156         if (data->external) {
2157                 writestruct(wd, DATA, CustomDataExternal, 1, data->external);
2158         }
2159 }
2160
2161 static void write_mesh(WriteData *wd, Mesh *mesh)
2162 {
2163         CustomDataLayer *vlayers = NULL, vlayers_buff[CD_TEMP_CHUNK_SIZE];
2164         CustomDataLayer *elayers = NULL, elayers_buff[CD_TEMP_CHUNK_SIZE];
2165         CustomDataLayer *flayers = NULL, flayers_buff[CD_TEMP_CHUNK_SIZE];
2166         CustomDataLayer *llayers = NULL, llayers_buff[CD_TEMP_CHUNK_SIZE];
2167         CustomDataLayer *players = NULL, players_buff[CD_TEMP_CHUNK_SIZE];
2168
2169         if (mesh->id.us > 0 || wd->use_memfile) {
2170                 /* write LibData */
2171                 {
2172                         /* write a copy of the mesh, don't modify in place because it is
2173                          * not thread safe for threaded renders that are reading this */
2174                         Mesh *old_mesh = mesh;
2175                         Mesh copy_mesh = *mesh;
2176                         mesh = &copy_mesh;
2177
2178                         /* cache only - don't write */
2179                         mesh->mface = NULL;
2180                         mesh->totface = 0;
2181                         memset(&mesh->fdata, 0, sizeof(mesh->fdata));
2182
2183                         /**
2184                          * Those calls:
2185                          *   - Reduce mesh->xdata.totlayer to number of layers to write.
2186                          *   - Fill xlayers with those layers to be written.
2187                          * Note that mesh->xdata is from now on invalid for Blender, but this is why the whole mesh is
2188                          * a temp local copy!
2189                          */
2190                         CustomData_file_write_prepare(&mesh->vdata, &vlayers, vlayers_buff, ARRAY_SIZE(vlayers_buff));
2191                         CustomData_file_write_prepare(&mesh->edata, &elayers, elayers_buff, ARRAY_SIZE(elayers_buff));
2192                         flayers = flayers_buff;
2193                         CustomData_file_write_prepare(&mesh->ldata, &llayers, llayers_buff, ARRAY_SIZE(llayers_buff));
2194                         CustomData_file_write_prepare(&mesh->pdata, &players, players_buff, ARRAY_SIZE(players_buff));
2195
2196                         writestruct_at_address(wd, ID_ME, Mesh, 1, old_mesh, mesh);
2197                         write_iddata(wd, &mesh->id);
2198
2199                         /* direct data */
2200                         if (mesh->adt) {
2201                                 write_animdata(wd, mesh->adt);
2202                         }
2203
2204                         writedata(wd, DATA, sizeof(void *) * mesh->totcol, mesh->mat);
2205                         writedata(wd, DATA, sizeof(MSelect) * mesh->totselect, mesh->mselect);
2206
2207                         write_customdata(wd, &mesh->id, mesh->totvert, &mesh->vdata, vlayers, -1, 0);
2208                         write_customdata(wd, &mesh->id, mesh->totedge, &mesh->edata, elayers, -1, 0);
2209                         /* fdata is really a dummy - written so slots align */
2210                         write_customdata(wd, &mesh->id, mesh->totface, &mesh->fdata, flayers, -1, 0);
2211                         write_customdata(wd, &mesh->id, mesh->totloop, &mesh->ldata, llayers, -1, 0);
2212                         write_customdata(wd, &mesh->id, mesh->totpoly, &mesh->pdata, players, -1, 0);
2213
2214                         /* restore pointer */
2215                         mesh = old_mesh;
2216                 }
2217         }
2218
2219         if (vlayers && vlayers != vlayers_buff) {
2220                 MEM_freeN(vlayers);
2221         }
2222         if (elayers && elayers != elayers_buff) {
2223                 MEM_freeN(elayers);
2224         }
2225         if (flayers && flayers != flayers_buff) {
2226                 MEM_freeN(flayers);
2227         }
2228         if (llayers && llayers != llayers_buff) {
2229                 MEM_freeN(llayers);
2230         }
2231         if (players && players != players_buff) {
2232                 MEM_freeN(players);
2233         }
2234 }
2235
2236 static void write_lattice(WriteData *wd, Lattice *lt)
2237 {
2238         if (lt->id.us > 0 || wd->use_memfile) {
2239                 /* write LibData */
2240                 writestruct(wd, ID_LT, Lattice, 1, lt);
2241                 write_iddata(wd, &lt->id);
2242
2243                 /* write animdata */
2244                 if (lt->adt) {
2245                         write_animdata(wd, lt->adt);
2246                 }
2247
2248                 /* direct data */
2249                 writestruct(wd, DATA, BPoint, lt->pntsu * lt->pntsv * lt->pntsw, lt->def);
2250
2251                 write_dverts(wd, lt->pntsu * lt->pntsv * lt->pntsw, lt->dvert);
2252         }
2253 }
2254
2255 static void write_image(WriteData *wd, Image *ima)
2256 {
2257         if (ima->id.us > 0 || wd->use_memfile) {
2258                 ImagePackedFile *imapf;
2259
2260                 /* Some trickery to keep forward compatibility of packed images. */
2261                 BLI_assert(ima->packedfile == NULL);
2262                 if (ima->packedfiles.first != NULL) {
2263                         imapf = ima->packedfiles.first;
2264                         ima->packedfile = imapf->packedfile;
2265                 }
2266
2267                 /* write LibData */
2268                 writestruct(wd, ID_IM, Image, 1, ima);
2269                 write_iddata(wd, &ima->id);
2270
2271                 for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next) {
2272                         writestruct(wd, DATA, ImagePackedFile, 1, imapf);
2273                         if (imapf->packedfile) {
2274                                 PackedFile *pf = imapf->packedfile;
2275                                 writestruct(wd, DATA, PackedFile, 1, pf);
2276                                 writedata(wd, DATA, pf->size, pf->data);
2277                         }
2278                 }
2279
2280                 write_previews(wd, ima->preview);
2281
2282                 for (ImageView *iv = ima->views.first; iv; iv = iv->next) {
2283                         writestruct(wd, DATA, ImageView, 1, iv);
2284                 }
2285                 writestruct(wd, DATA, Stereo3dFormat, 1, ima->stereo3d_format);
2286
2287                 ima->packedfile = NULL;
2288
2289                 writelist(wd, DATA, RenderSlot, &ima->renderslots);
2290         }
2291 }
2292
2293 static void write_texture(WriteData *wd, Tex *tex)
2294 {
2295         if (tex->id.us > 0 || wd->use_memfile) {
2296                 /* write LibData */
2297                 writestruct(wd, ID_TE, Tex, 1, tex);
2298                 write_iddata(wd, &tex->id);
2299
2300                 if (tex->adt) {
2301                         write_animdata(wd, tex->adt);
2302                 }
2303
2304                 /* direct data */
2305                 if (tex->coba) {
2306                         writestruct(wd, DATA, ColorBand, 1, tex->coba);
2307                 }
2308
2309                 /* nodetree is integral part of texture, no libdata */
2310                 if (tex->nodetree) {
2311                         writestruct(wd, DATA, bNodeTree, 1, tex->nodetree);
2312                         write_nodetree_nolib(wd, tex->nodetree);
2313                 }
2314
2315                 write_previews(wd, tex->preview);
2316         }
2317 }
2318
2319 static void write_material(WriteData *wd, Material *ma)
2320 {
2321         if (ma->id.us > 0 || wd->use_memfile) {
2322                 /* write LibData */
2323                 writestruct(wd, ID_MA, Material, 1, ma);
2324                 write_iddata(wd, &ma->id);
2325
2326                 if (ma->adt) {
2327                         write_animdata(wd, ma->adt);
2328                 }
2329
2330                 /* nodetree is integral part of material, no libdata */
2331                 if (ma->nodetree) {
2332                         writestruct(wd, DATA, bNodeTree, 1, ma->nodetree);
2333                         write_nodetree_nolib(wd, ma->nodetree);
2334                 }
2335
2336                 write_previews(wd, ma->preview);
2337
2338                 /* grease pencil settings */
2339                 if (ma->gp_style) {
2340                         writestruct(wd, DATA, MaterialGPencilStyle, 1, ma->gp_style);
2341                 }
2342         }
2343 }
2344
2345 static void write_world(WriteData *wd, World *wrld)
2346 {
2347         if (wrld->id.us > 0 || wd->use_memfile) {
2348                 /* write LibData */
2349                 writestruct(wd, ID_WO, World, 1, wrld);
2350                 write_iddata(wd, &wrld->id);
2351
2352                 if (wrld->adt) {
2353                         write_animdata(wd, wrld->adt);
2354                 }
2355
2356                 /* nodetree is integral part of world, no libdata */
2357                 if (wrld->nodetree) {
2358                         writestruct(wd, DATA, bNodeTree, 1, wrld->nodetree);
2359                         write_nodetree_nolib(wd, wrld->nodetree);
2360                 }
2361
2362                 write_previews(wd, wrld->preview);
2363         }
2364 }
2365
2366 static void write_lamp(WriteData *wd, Lamp *la)
2367 {
2368         if (la->id.us > 0 || wd->use_memfile) {
2369                 /* write LibData */
2370                 writestruct(wd, ID_LA, Lamp, 1, la);
2371                 write_iddata(wd, &la->id);
2372
2373                 if (la->adt) {
2374                         write_animdata(wd, la->adt);
2375                 }
2376
2377                 if (la->curfalloff) {
2378                         write_curvemapping(wd, la->curfalloff);
2379                 }
2380
2381                 /* nodetree is integral part of lamps, no libdata */
2382                 if (la->nodetree) {
2383                         writestruct(wd, DATA, bNodeTree, 1, la->nodetree);
2384                         write_nodetree_nolib(wd, la->nodetree);
2385                 }
2386
2387                 write_previews(wd, la->preview);
2388         }
2389 }
2390
2391 static void write_collection_nolib(WriteData *wd, Collection *collection)
2392 {
2393         /* Shared function for collection datablocks and scene master collection. */
2394         write_previews(wd, collection->preview);
2395
2396         for (CollectionObject *cob = collection->gobject.first; cob; cob = cob->next) {
2397                 writestruct(wd, DATA, CollectionObject, 1, cob);
2398         }
2399
2400         for (CollectionChild *child = collection->children.first; child; child = child->next) {
2401                 writestruct(wd, DATA, CollectionChild, 1, child);
2402         }
2403 }
2404
2405 static void write_collection(WriteData *wd, Collection *collection)
2406 {
2407         if (collection->id.us > 0 || wd->use_memfile) {
2408                 /* write LibData */
2409                 writestruct(wd, ID_GR, Collection, 1, collection);
2410                 write_iddata(wd, &collection->id);
2411
2412                 write_collection_nolib(wd, collection);
2413         }
2414 }
2415
2416 static void write_sequence_modifiers(WriteData *wd, ListBase *modbase)
2417 {
2418         SequenceModifierData *smd;
2419
2420         for (smd = modbase->first; smd; smd = smd->next) {
2421                 const SequenceModifierTypeInfo *smti = BKE_sequence_modifier_type_info_get(smd->type);
2422
2423                 if (smti) {
2424                         writestruct_id(wd, DATA, smti->struct_name, 1, smd);
2425
2426                         if (smd->type == seqModifierType_Curves) {
2427                                 CurvesModifierData *cmd = (CurvesModifierData *)smd;
2428
2429                                 write_curvemapping(wd, &cmd->curve_mapping);
2430                         }
2431                         else if (smd->type == seqModifierType_HueCorrect) {
2432                                 HueCorrectModifierData *hcmd = (HueCorrectModifierData *)smd;
2433
2434                                 write_curvemapping(wd, &hcmd->curve_mapping);
2435                         }
2436                 }
2437                 else {
2438                         writestruct(wd, DATA, SequenceModifierData, 1, smd);
2439                 }
2440         }
2441 }
2442
2443 static void write_view_settings(WriteData *wd, ColorManagedViewSettings *view_settings)
2444 {
2445         if (view_settings->curve_mapping) {
2446                 write_curvemapping(wd, view_settings->curve_mapping);
2447         }
2448 }
2449
2450 static void write_paint(WriteData *wd, Paint *p)
2451 {
2452         if (p->cavity_curve) {
2453                 write_curvemapping(wd, p->cavity_curve);
2454         }
2455         writedata(wd, DATA, sizeof(PaintToolSlot) * p->tool_slots_len, p->tool_slots);
2456 }
2457
2458 static void write_layer_collections(WriteData *wd, ListBase *lb)
2459 {
2460         for (LayerCollection *lc = lb->first; lc; lc = lc->next) {
2461                 writestruct(wd, DATA, LayerCollection, 1, lc);
2462
2463                 write_layer_collections(wd, &lc->layer_collections);
2464         }
2465 }
2466
2467 static void write_view_layer(WriteData *wd, ViewLayer *view_layer)
2468 {
2469         writestruct(wd, DATA, ViewLayer, 1, view_layer);
2470         writelist(wd, DATA, Base, &view_layer->object_bases);
2471
2472         if (view_layer->id_properties) {
2473                 IDP_WriteProperty(view_layer->id_properties, wd);
2474         }
2475
2476         for (FreestyleModuleConfig *fmc = view_layer->freestyle_config.modules.first; fmc; fmc = fmc->next) {
2477                 writestruct(wd, DATA, FreestyleModuleConfig, 1, fmc);
2478         }
2479
2480         for (FreestyleLineSet *fls = view_layer->freestyle_config.linesets.first; fls; fls = fls->next) {
2481                 writestruct(wd, DATA, FreestyleLineSet, 1, fls);
2482         }
2483         write_layer_collections(wd, &view_layer->layer_collections);
2484 }
2485
2486 static void write_lightcache_texture(WriteData *wd, LightCacheTexture *tex)
2487 {
2488         if (tex->data) {
2489                 size_t data_size = tex->components * tex->tex_size[0] * tex->tex_size[1] * tex->tex_size[2];
2490                 if (tex->data_type == LIGHTCACHETEX_FLOAT) {
2491                         data_size *= sizeof(float);
2492                 }
2493                 else if (tex->data_type == LIGHTCACHETEX_UINT) {
2494                         data_size *= sizeof(uint);
2495                 }
2496                 writedata(wd, DATA, data_size, tex->data);
2497         }
2498 }
2499
2500 static void write_lightcache(WriteData *wd, LightCache *cache)
2501 {
2502         write_lightcache_texture(wd, &cache->grid_tx);
2503         write_lightcache_texture(wd, &cache->cube_tx);
2504
2505         if (cache->cube_mips) {
2506                 writestruct(wd, DATA, LightCacheTexture, cache->mips_len, cache->cube_mips);
2507                 for (int i = 0; i < cache->mips_len; ++i) {
2508                         write_lightcache_texture(wd, &cache->cube_mips[i]);
2509                 }
2510         }
2511
2512         writestruct(wd, DATA, LightGridCache,    cache->grid_len, cache->grid_data);
2513         writestruct(wd, DATA, LightProbeCache,   cache->cube_len, cache->cube_data);
2514 }
2515
2516 static void write_scene(WriteData *wd, Scene *sce)
2517 {
2518         /* write LibData */
2519         writestruct(wd, ID_SCE, Scene, 1, sce);
2520         write_iddata(wd, &sce->id);
2521
2522         if (sce->adt) {
2523                 write_animdata(wd, sce->adt);
2524         }
2525         write_keyingsets(wd, &sce->keyingsets);
2526
2527         /* direct data */
2528         ToolSettings *tos = sce->toolsettings;
2529         writestruct(wd, DATA, ToolSettings, 1, tos);
2530         if (tos->vpaint) {
2531                 writestruct(wd, DATA, VPaint, 1, tos->vpaint);
2532                 write_paint(wd, &tos->vpaint->paint);
2533         }
2534         if (tos->wpaint) {
2535                 writestruct(wd, DATA, VPaint, 1, tos->wpaint);
2536                 write_paint(wd, &tos->wpaint->paint);
2537         }
2538         if (tos->sculpt) {
2539                 writestruct(wd, DATA, Sculpt, 1, tos->sculpt);
2540                 write_paint(wd, &tos->sculpt->paint);
2541         }
2542         if (tos->uvsculpt) {
2543                 writestruct(wd, DATA, UvSculpt, 1, tos->uvsculpt);
2544                 write_paint(wd, &tos->uvsculpt->paint);
2545         }
2546         if (tos->gp_paint) {
2547                 writestruct(wd, DATA, GpPaint, 1, tos->gp_paint);
2548                 write_paint(wd, &tos->gp_paint->paint);
2549         }
2550         /* write grease-pencil custom ipo curve to file */
2551         if (tos->gp_interpolate.custom_ipo) {
2552                 write_curvemapping(wd, tos->gp_interpolate.custom_ipo);
2553         }
2554         /* write grease-pencil multiframe falloff curve to file */
2555         if (tos->gp_sculpt.cur_falloff) {
2556                 write_curvemapping(wd, tos->gp_sculpt.cur_falloff);
2557         }
2558
2559         write_paint(wd, &tos->imapaint.paint);
2560
2561         Editing *ed = sce->ed;
2562         if (ed) {
2563                 Sequence *seq;
2564
2565                 writestruct(wd, DATA, Editing, 1, ed);
2566
2567                 /* reset write flags too */
2568
2569                 SEQ_BEGIN(ed, seq)
2570                 {
2571                         if (seq->strip) {
2572                                 seq->strip->done = false;
2573                         }
2574                         writestruct(wd, DATA, Sequence, 1, seq);
2575                 } SEQ_END;
2576
2577                 SEQ_BEGIN(ed, seq)
2578                 {
2579                         if (seq->strip && seq->strip->done == 0) {
2580                                 /* write strip with 'done' at 0 because readfile */
2581
2582                                 if (seq->effectdata) {
2583                                         switch (seq->type) {
2584                                                 case SEQ_TYPE_COLOR:
2585                                                         writestruct(wd, DATA, SolidColorVars, 1, seq->effectdata);
2586                                                         break;
2587                                                 case SEQ_TYPE_SPEED:
2588                                                         writestruct(wd, DATA, SpeedControlVars, 1, seq->effectdata);
2589                                                         break;
2590                                                 case SEQ_TYPE_WIPE:
2591                                                         writestruct(wd, DATA, WipeVars, 1, seq->effectdata);
2592                                                         break;
2593                                                 case SEQ_TYPE_GLOW:
2594                                                         writestruct(wd, DATA, GlowVars, 1, seq->effectdata);
2595                                                         break;
2596                                                 case SEQ_TYPE_TRANSFORM:
2597                                                         writestruct(wd, DATA, TransformVars, 1, seq->effectdata);
2598                                                         break;
2599                                                 case SEQ_TYPE_GAUSSIAN_BLUR:
2600                                                         writestruct(wd, DATA, GaussianBlurVars, 1, seq->effectdata);
2601                                                         break;
2602                                                 case SEQ_TYPE_TEXT:
2603                                                         writestruct(wd, DATA, TextVars, 1, seq->effectdata);
2604                                                         break;
2605                                                 case SEQ_TYPE_COLORMIX:
2606                                                         writestruct(wd, DATA, ColorMixVars, 1, seq->effectdata);
2607                                                         break;
2608                                         }
2609                                 }
2610
2611                                 writestruct(wd, DATA, Stereo3dFormat, 1, seq->stereo3d_format);
2612
2613                                 Strip *strip = seq->strip;
2614                                 writestruct(wd, DATA, Strip, 1, strip);
2615                                 if (seq->flag & SEQ_USE_CROP && strip->crop) {
2616                                         writestruct(wd, DATA, StripCrop, 1, strip->crop);
2617                                 }
2618                                 if (seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
2619                                         writestruct(wd, DATA, StripTransform, 1, strip->transform);
2620                                 }
2621                                 if (seq->flag & SEQ_USE_PROXY && strip->proxy) {
2622                                         writestruct(wd, DATA, StripProxy, 1, strip->proxy);
2623                                 }
2624                                 if (seq->type == SEQ_TYPE_IMAGE) {
2625                                         writestruct(wd, DATA, StripElem,
2626                                                     MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem),
2627                                                     strip->stripdata);
2628                                 }
2629                                 else if (ELEM(seq->type, SEQ_TYPE_MOVIE, SEQ_TYPE_SOUND_RAM, SEQ_TYPE_SOUND_HD)) {
2630                                         writestruct(wd, DATA, StripElem, 1, strip->stripdata);
2631                                 }
2632
2633                                 strip->done = true;
2634                         }
2635
2636                         if (seq->prop) {
2637                                 IDP_WriteProperty(seq->prop, wd);
2638                         }
2639
2640                         write_sequence_modifiers(wd, &seq->modifiers);
2641                 } SEQ_END;
2642
2643                 /* new; meta stack too, even when its nasty restore code */
2644                 for (MetaStack *ms = ed->metastack.first; ms; ms = ms->next) {
2645                         writestruct(wd, DATA, MetaStack, 1, ms);
2646                 }
2647         }
2648
2649         if (sce->r.avicodecdata) {
2650                 writestruct(wd, DATA, AviCodecData, 1, sce->r.avicodecdata);
2651                 if (sce->r.avicodecdata->lpFormat) {
2652                         writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
2653                 }
2654                 if (sce->r.avicodecdata->lpParms) {
2655                         writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
2656                 }
2657         }
2658         if (sce->r.ffcodecdata.properties) {
2659                 IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
2660         }
2661
2662         /* writing dynamic list of TimeMarkers to the blend file */
2663         for (TimeMarker *marker = sce->markers.first; marker; marker = marker->next) {
2664                 writestruct(wd, DATA, TimeMarker, 1, marker);
2665         }
2666
2667         /* writing dynamic list of TransformOrientations to the blend file */
2668         for (TransformOrientation *ts = sce->transform_spaces.first; ts; ts = ts->next) {
2669                 writestruct(wd, DATA, TransformOrientation, 1, ts);
2670         }
2671
2672         /* writing MultiView to the blend file */
2673         for (SceneRenderView *srv = sce->r.views.first; srv; srv = srv->next) {
2674                 writestruct(wd, DATA, SceneRenderView, 1, srv);
2675         }
2676
2677         if (sce->nodetree) {
2678                 writestruct(wd, DATA, bNodeTree, 1, sce->nodetree);
2679                 write_nodetree_nolib(wd, sce->nodetree);
2680         }
2681
2682         write_view_settings(wd, &sce->view_settings);
2683
2684         /* writing RigidBodyWorld data to the blend file */
2685         if (sce->rigidbody_world) {
2686                 /* Set deprecated pointers to prevent crashes of older Blenders */
2687                 sce->rigidbody_world->pointcache = sce->rigidbody_world->shared->pointcache;
2688                 sce->rigidbody_world->ptcaches = sce->rigidbody_world->shared->ptcaches;
2689                 writestruct(wd, DATA, RigidBodyWorld, 1, sce->rigidbody_world);
2690
2691                 writestruct(wd, DATA, RigidBodyWorld_Shared, 1, sce->rigidbody_world->shared);
2692                 writestruct(wd, DATA, EffectorWeights, 1, sce->rigidbody_world->effector_weights);
2693                 write_pointcaches(wd, &(sce->rigidbody_world->shared->ptcaches));
2694         }
2695
2696         write_previews(wd, sce->preview);
2697         write_curvemapping_curves(wd, &sce->r.mblur_shutter_curve);
2698
2699         for (ViewLayer *view_layer = sce->view_layers.first; view_layer; view_layer = view_layer->next) {
2700                 write_view_layer(wd, view_layer);
2701         }
2702
2703         if (sce->master_collection) {
2704                 writestruct(wd, DATA, Collection, 1, sce->master_collection);
2705                 write_collection_nolib(wd, sce->master_collection);
2706         }
2707
2708         /* Eevee Lightcache */
2709         if (sce->eevee.light_cache && !wd->use_memfile) {
2710                 writestruct(wd, DATA, LightCache, 1, sce->eevee.light_cache);
2711                 write_lightcache(wd, sce->eevee.light_cache);
2712         }
2713
2714         /* Freed on doversion. */
2715         BLI_assert(sce->layer_properties == NULL);
2716 }
2717
2718 static void write_gpencil(WriteData *wd, bGPdata *gpd)
2719 {
2720         if (gpd->id.us > 0 || wd->use_memfile) {
2721                 /* write gpd data block to file */
2722                 writestruct(wd, ID_GD, bGPdata, 1, gpd);
2723                 write_iddata(wd, &gpd->id);
2724
2725                 if (gpd->adt) {
2726                         write_animdata(wd, gpd->adt);
2727                 }
2728
2729                 writedata(wd, DATA, sizeof(void *) * gpd->totcol, gpd->mat);
2730
2731                 /* write grease-pencil layers to file */
2732                 writelist(wd, DATA, bGPDlayer, &gpd->layers);
2733                 for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) {
2734                         /* write this layer's frames to file */
2735                         writelist(wd, DATA, bGPDframe, &gpl->frames);
2736                         for (bGPDframe *gpf = gpl->frames.first; gpf; gpf = gpf->next) {
2737                                 /* write strokes */
2738                                 writelist(wd, DATA, bGPDstroke, &gpf->strokes);
2739                                 for (bGPDstroke *gps = gpf->strokes.first; gps; gps = gps->next) {
2740                                         writestruct(wd, DATA, bGPDspoint, gps->totpoints, gps->points);
2741                                         write_dverts(wd, gps->totpoints, gps->dvert);
2742                                 }
2743                         }
2744                 }
2745         }
2746 }
2747
2748 static void write_region(WriteData *wd, ARegion *ar, int spacetype)
2749 {
2750         writestruct(wd, DATA, ARegion, 1, ar);
2751
2752         if (ar->regiondata) {
2753                 if (ar->flag & RGN_FLAG_TEMP_REGIONDATA) {
2754                         return;
2755                 }
2756
2757                 switch (spacetype) {
2758                         case SPACE_VIEW3D:
2759                                 if (ar->regiontype == RGN_TYPE_WINDOW) {
2760                                         RegionView3D *rv3d = ar->regiondata;
2761                                         writestruct(wd, DATA, RegionView3D, 1, rv3d);
2762
2763                                         if (rv3d->localvd) {
2764                                                 writestruct(wd, DATA, RegionView3D, 1, rv3d->localvd);
2765                                         }
2766                                         if (rv3d->clipbb) {
2767                                                 writestruct(wd, DATA, BoundBox, 1, rv3d->clipbb);
2768                                         }
2769
2770                                 }
2771                                 else
2772                                         printf("regiondata write missing!\n");
2773                                 break;
2774                         default:
2775                                 printf("regiondata write missing!\n");
2776                 }
2777         }
2778 }
2779
2780 static void write_uilist(WriteData *wd, uiList *ui_list)
2781 {
2782         writestruct(wd, DATA, uiList, 1, ui_list);
2783
2784         if (ui_list->properties) {
2785                 IDP_WriteProperty(ui_list->properties, wd);
2786         }
2787 }
2788
2789 static void write_soops(WriteData *wd, SpaceOops *so)
2790 {
2791         BLI_mempool *ts = so->treestore;
2792
2793         if (ts) {
2794                 SpaceOops so_flat = *so;
2795
2796                 int elems = BLI_mempool_len(ts);
2797                 /* linearize mempool to array */
2798                 TreeStoreElem *data = elems ? BLI_mempool_as_arrayN(ts, "TreeStoreElem") : NULL;
2799
2800                 if (data) {
2801                         /* In this block we use the memory location of the treestore
2802                          * but _not_ its data, the addresses in this case are UUID's,
2803                          * since we can't rely on malloc giving us different values each time.
2804                          */
2805                         TreeStore ts_flat = {0};
2806
2807                         /* we know the treestore is at least as big as a pointer,
2808                          * so offsetting works to give us a UUID. */
2809                         void *data_addr = (void *)POINTER_OFFSET(ts, sizeof(void *));
2810
2811                         ts_flat.usedelem = elems;
2812                         ts_flat.totelem = elems;
2813                         ts_flat.data = data_addr;
2814
2815                         writestruct(wd, DATA, SpaceOops, 1, so);
2816
2817                         writestruct_at_address(wd, DATA, TreeStore, 1, ts, &ts_flat);
2818                         writestruct_at_address(wd, DATA, TreeStoreElem, elems, data_addr, data);
2819
2820                         MEM_freeN(data);
2821                 }
2822                 else {
2823                         so_flat.treestore = NULL;
2824                         writestruct_at_address(wd, DATA, SpaceOops, 1, so, &so_flat);
2825                 }
2826         }
2827         else {
2828                 writestruct(wd, DATA, SpaceOops, 1, so);
2829         }
2830 }
2831
2832 static void write_panel_list(WriteData *wd, ListBase *lb)
2833 {
2834         for (Panel *pa = lb->first; pa; pa = pa->next) {
2835                 writestruct(wd, DATA, Panel, 1, pa);
2836                 write_panel_list(wd, &pa->children);
2837         }
2838 }
2839
2840 static void write_area_regions(WriteData *wd, ScrArea *area)
2841 {
2842         for (ARegion *region = area->regionbase.first; region; region = region->next) {
2843                 write_region(wd, region, area->spacetype);
2844                 write_panel_list(wd, &region->panels);
2845
2846                 for (PanelCategoryStack *pc_act = region->panels_category_active.first; pc_act; pc_act = pc_act->next) {
2847                         writestruct(wd, DATA, PanelCategoryStack, 1, pc_act);
2848                 }
2849
2850                 for (uiList *ui_list = region->ui_lists.first; ui_list; ui_list = ui_list->next) {
2851                         write_uilist(wd, ui_list);
2852                 }
2853
2854                 for (uiPreview *ui_preview = region->ui_previews.first; ui_preview; ui_preview = ui_preview->next) {
2855                         writestruct(wd, DATA, uiPreview, 1, ui_preview);
2856                 }
2857         }
2858
2859         for (SpaceLink *sl = area->spacedata.first; sl; sl = sl->next) {
2860                 for (ARegion *region = sl->regionbase.first; region; region = region->next) {
2861                         write_region(wd, region, sl->spacetype);
2862                 }
2863
2864                 if (sl->spacetype == SPACE_VIEW3D) {
2865                         View3D *v3d = (View3D *)sl;
2866                         writestruct(wd, DATA, View3D, 1, v3d);
2867
2868                         if (v3d->localvd) {
2869                                 writestruct(wd, DATA, View3D, 1, v3d->localvd);
2870                         }
2871
2872                         if (v3d->fx_settings.ssao) {
2873                                 writestruct(wd, DATA, GPUSSAOSettings, 1, v3d->fx_settings.ssao);
2874                         }
2875                         if (v3d->fx_settings.dof) {
2876                                 writestruct(wd, DATA, GPUDOFSettings, 1, v3d->fx_settings.dof);
2877                         }
2878                 }
2879                 else if (sl->spacetype == SPACE_IPO) {
2880                         SpaceIpo *sipo = (SpaceIpo *)sl;
2881                         ListBase tmpGhosts = sipo->runtime.ghost_curves;
2882
2883                         /* temporarily disable ghost curves when saving */
2884                         BLI_listbase_clear(&sipo->runtime.ghost_curves);
2885
2886                         writestruct(wd, DATA, SpaceIpo, 1, sl);
2887                         if (sipo->ads) {
2888                                 writestruct(wd, DATA, bDopeSheet, 1, sipo->ads);
2889                         }
2890
2891                         /* reenable ghost curves */
2892                         sipo->runtime.ghost_curves = tmpGhosts;
2893                 }
2894                 else if (sl->spacetype == SPACE_BUTS) {
2895                         writestruct(wd, DATA, SpaceButs, 1, sl);
2896                 }
2897                 else if (sl->spacetype == SPACE_FILE) {
2898                         SpaceFile *sfile = (SpaceFile *)sl;
2899
2900                         writestruct(wd, DATA, SpaceFile, 1, sl);
2901                         if (sfile->params) {
2902                                 writestruct(wd, DATA, FileSelectParams, 1, sfile->params);
2903                         }
2904                 }
2905                 else if (sl->spacetype == SPACE_SEQ) {
2906                         writestruct(wd, DATA, SpaceSeq, 1, sl);
2907                 }
2908                 else if (sl->spacetype == SPACE_OUTLINER) {
2909                         SpaceOops *so = (SpaceOops *)sl;
2910                         write_soops(wd, so);
2911                 }
2912                 else if (sl->spacetype == SPACE_IMAGE) {
2913                         writestruct(wd, DATA, SpaceImage, 1, sl);
2914                 }
2915                 else if (sl->spacetype == SPACE_TEXT) {
2916                         writestruct(wd, DATA, SpaceText, 1, sl);
2917                 }
2918                 else if (sl->spacetype == SPACE_SCRIPT) {
2919                         SpaceScript *scr = (SpaceScript *)sl;
2920                         scr->but_refs = NULL;
2921                         writestruct(wd, DATA, SpaceScript, 1, sl);
2922                 }
2923                 else if (sl->spacetype == SPACE_ACTION) {
2924                         writestruct(wd, DATA, SpaceAction, 1, sl);
2925                 }
2926                 else if (sl->spacetype == SPACE_NLA) {
2927                         SpaceNla *snla = (SpaceNla *)sl;
2928
2929                         writestruct(wd, DATA, SpaceNla, 1, snla);
2930                         if (snla->ads) {
2931                                 writestruct(wd, DATA, bDopeSheet, 1, snla->ads);
2932                         }
2933                 }
2934                 else if (sl->spacetype == SPACE_NODE) {
2935                         SpaceNode *snode = (SpaceNode *)sl;
2936                         bNodeTreePath *path;
2937                         writestruct(wd, DATA, SpaceNode, 1, snode);
2938
2939                         for (path = snode->treepath.first; path; path = path->next) {
2940                                 writestruct(wd, DATA, bNodeTreePath, 1, path);
2941                         }
2942                 }
2943                 else if (sl->spacetype == SPACE_CONSOLE) {
2944                         SpaceConsole *con = (SpaceConsole *)sl;
2945                         ConsoleLine *cl;
2946
2947                         for (cl = con->history.first; cl; cl = cl->next) {
2948                                 /* 'len_alloc' is invalid on write, set from 'len' on read */
2949                                 writestruct(wd, DATA, ConsoleLine, 1, cl);
2950                                 writedata(wd, DATA, cl->len + 1, cl->line);
2951                         }
2952                         writestruct(wd, DATA, SpaceConsole, 1, sl);
2953                 }
2954 #ifdef WITH_GLOBAL_AREA_WRITING
2955                 else if (sl->spacetype == SPACE_TOPBAR) {
2956                         writestruct(wd, DATA, SpaceTopBar, 1, sl);
2957                 }
2958                 else if (sl->spacetype == SPACE_STATUSBAR) {
2959                         writestruct(wd, DATA, SpaceStatusBar, 1, sl);
2960                 }
2961 #endif
2962                 else if (sl->spacetype == SPACE_USERPREF) {
2963                         writestruct(wd, DATA, SpaceUserPref, 1, sl);
2964                 }
2965                 else if (sl->spacetype == SPACE_CLIP) {
2966                         writestruct(wd, DATA, SpaceClip, 1, sl);
2967                 }
2968                 else if (sl->spacetype == SPACE_INFO) {
2969                         writestruct(wd, DATA, SpaceInfo, 1, sl);
2970                 }
2971         }
2972 }
2973
2974 static void write_area_map(WriteData *wd, ScrAreaMap *area_map)
2975 {
2976         writelist(wd, DATA, ScrVert, &area_map->vertbase);
2977         writelist(wd, DATA, ScrEdge, &area_map->edgebase);
2978         for (ScrArea *area = area_map->areabase.first; area; area = area->next) {
2979                 area->butspacetype = area->spacetype; /* Just for compatibility, will be reset below. */
2980
2981                 writestruct(wd, DATA, ScrArea, 1, area);
2982
2983 #ifdef WITH_GLOBAL_AREA_WRITING
2984                 writestruct(wd, DATA, ScrGlobalAreaData, 1, area->global);
2985 #endif
2986
2987                 write_area_regions(wd, area);
2988
2989                 area->butspacetype = SPACE_EMPTY; /* Unset again, was changed above. */
2990         }
2991 }
2992
2993 static void write_windowmanager(WriteData *wd, wmWindowManager *wm)
2994 {
2995         writestruct(wd, ID_WM, wmWindowManager, 1, wm);
2996         write_iddata(wd, &wm->id);
2997
2998         for (wmWindow *win = wm->windows.first; win; win = win->next) {
2999 #ifndef WITH_GLOBAL_AREA_WRITING
3000                 /* Don't write global areas yet, while we make changes to them. */
3001                 ScrAreaMap global_areas = win->global_areas;
3002                 memset(&win->global_areas, 0, sizeof(win->global_areas));
3003 #endif
3004
3005                 /* update deprecated screen member (for so loading in 2.7x uses the correct screen) */
3006                 win->screen = BKE_workspace_active_screen_get(win->workspace_hook);
3007
3008                 writestruct(wd, DATA, wmWindow, 1, win);
3009                 writestruct(wd, DATA, WorkSpaceInstanceHook, 1, win->workspace_hook);
3010                 writestruct(wd, DATA, Stereo3dFormat, 1, win->stereo3d_format);
3011
3012 #ifdef WITH_GLOBAL_AREA_WRITING
3013                 write_area_map(wd, &win->global_areas);
3014 #else
3015                 win->global_areas = global_areas;
3016 #endif
3017
3018                 /* data is written, clear deprecated data again */
3019                 win->screen = NULL;
3020         }
3021 }
3022
3023 static void write_screen(WriteData *wd, bScreen *sc)
3024 {
3025         /* Screens are reference counted, only saved if used by a workspace. */
3026         if (sc->id.us > 0 || wd->use_memfile) {
3027                 /* write LibData */
3028                 /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
3029                 writestruct(wd, ID_SCRN, bScreen, 1, sc);
3030                 write_iddata(wd, &sc->id);
3031
3032                 write_previews(wd, sc->preview);
3033
3034                 /* direct data */
3035                 write_area_map(wd, AREAMAP_FROM_SCREEN(sc));
3036         }
3037 }
3038
3039 static void write_bone(WriteData *wd, Bone *bone)
3040 {
3041         /* PATCH for upward compatibility after 2.37+ armature recode */
3042         bone->size[0] = bone->size[1] = bone->size[2] = 1.0f;
3043
3044         /* Write this bone */
3045         writestruct(wd, DATA, Bone, 1, bone);
3046
3047         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
3048          * of library blocks that implement this.*/
3049         if (bone->prop) {
3050                 IDP_WriteProperty(bone->prop, wd);
3051         }
3052
3053         /* Write Children */
3054         for (Bone *cbone = bone->childbase.first; cbone; cbone = cbone->next) {
3055                 write_bone(wd, cbone);
3056         }
3057 }
3058
3059 static void write_armature(WriteData *wd, bArmature *arm)
3060 {
3061         if (arm->id.us > 0 || wd->use_memfile) {
3062                 writestruct(wd, ID_AR, bArmature, 1, arm);
3063                 write_iddata(wd, &arm->id);
3064
3065                 if (arm->adt) {
3066                         write_animdata(wd, arm->adt);
3067                 }
3068
3069                 /* Direct data */
3070                 for (Bone *bone = arm->bonebase.first; bone; bone = bone->next) {
3071                         write_bone(wd, bone);
3072                 }
3073         }
3074 }
3075
3076 static void write_text(WriteData *wd, Text *text)
3077 {
3078         if ((text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) {
3079                 text->flags &= ~TXT_ISEXT;
3080         }
3081
3082         /* write LibData */
3083         writestruct(wd, ID_TXT, Text, 1, text);
3084         write_iddata(wd, &text->id);
3085
3086         if (text->name) {
3087                 writedata(wd, DATA, strlen(text->name) + 1, text->name);
3088         }
3089
3090         if (!(text->flags & TXT_ISEXT)) {
3091                 /* now write the text data, in two steps for optimization in the readfunction */
3092                 for (TextLine *tmp = text->lines.first; tmp; tmp = tmp->next) {
3093                         writestruct(wd, DATA, TextLine, 1, tmp);
3094                 }
3095
3096                 for (TextLine *tmp = text->lines.first; tmp; tmp = tmp->next) {
3097                         writedata(wd, DATA, tmp->len + 1, tmp->line);
3098                 }
3099         }
3100 }
3101
3102 static void write_speaker(WriteData *wd, Speaker *spk)
3103 {
3104         if (spk->id.us > 0 || wd->use_memfile) {
3105                 /* write LibData */
3106                 writestruct(wd, ID_SPK, Speaker, 1, spk);
3107                 write_iddata(wd, &spk->id);
3108