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