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