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