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