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: amount 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 */
916         sock->stack_type = 1;
917
918         if (node->type == NODE_GROUP) {
919                 bNodeTree *ngroup = (bNodeTree *)node->id;
920                 if (ngroup) {
921                         /* for node groups: look up the deprecated groupsock pointer */
922                         sock->groupsock = ntreeFindSocketInterface(ngroup, sock->in_out, sock->identifier);
923                         BLI_assert(sock->groupsock != NULL);
924
925                         /* node group sockets now use the generic identifier string to verify group nodes,
926                          * old blender uses the own_index.
927                          */
928                         sock->own_index = sock->groupsock->own_index;
929                 }
930         }
931 #endif
932
933         /* actual socket writing */
934         writestruct(wd, DATA, bNodeSocket, 1, sock);
935
936         if (sock->prop) {
937                 IDP_WriteProperty(sock->prop, wd);
938         }
939
940         if (sock->default_value) {
941                 writedata(wd, DATA, MEM_allocN_len(sock->default_value), sock->default_value);
942         }
943 }
944 static void write_node_socket_interface(WriteData *wd, bNodeTree *UNUSED(ntree), bNodeSocket *sock)
945 {
946 #ifdef USE_NODE_COMPAT_CUSTOMNODES
947         /* forward compatibility code, so older blenders still open */
948         sock->stack_type = 1;
949
950         /* Reconstruct the deprecated default_value structs in socket interface DNA. */
951         if (sock->default_value == NULL && sock->typeinfo) {
952                 node_socket_init_default_value(sock);
953         }
954 #endif
955
956         /* actual socket writing */
957         writestruct(wd, DATA, bNodeSocket, 1, sock);
958
959         if (sock->prop) {
960                 IDP_WriteProperty(sock->prop, wd);
961         }
962
963         if (sock->default_value) {
964                 writedata(wd, DATA, MEM_allocN_len(sock->default_value), sock->default_value);
965         }
966 }
967 /* this is only direct data, tree itself should have been written */
968 static void write_nodetree(WriteData *wd, bNodeTree *ntree)
969 {
970         bNode *node;
971         bNodeSocket *sock;
972         bNodeLink *link;
973
974         /* for link_list() speed, we write per list */
975
976         if (ntree->adt) {
977                 write_animdata(wd, ntree->adt);
978         }
979
980         for (node = ntree->nodes.first; node; node = node->next) {
981                 writestruct(wd, DATA, bNode, 1, node);
982
983                 if (node->prop) {
984                         IDP_WriteProperty(node->prop, wd);
985                 }
986
987                 for (sock = node->inputs.first; sock; sock = sock->next) {
988                         write_node_socket(wd, ntree, node, sock);
989                 }
990                 for (sock = node->outputs.first; sock; sock = sock->next) {
991                         write_node_socket(wd, ntree, node, sock);
992                 }
993
994                 for (link = node->internal_links.first; link; link = link->next) {
995                         writestruct(wd, DATA, bNodeLink, 1, link);
996                 }
997
998                 if (node->storage) {
999                         /* could be handlerized at some point, now only 1 exception still */
1000                         if ((ntree->type == NTREE_SHADER) &&
1001                             ELEM(node->type, SH_NODE_CURVE_VEC, SH_NODE_CURVE_RGB))
1002                         {
1003                                 write_curvemapping(wd, node->storage);
1004                         }
1005                         else if (ntree->type == NTREE_SHADER &&
1006                                  (node->type == SH_NODE_SCRIPT))
1007                         {
1008                                 NodeShaderScript *nss = (NodeShaderScript *)node->storage;
1009                                 if (nss->bytecode) {
1010                                         writedata(wd, DATA, strlen(nss->bytecode) + 1, nss->bytecode);
1011                                 }
1012                                 writestruct_id(wd, DATA, node->typeinfo->storagename, 1, node->storage);
1013                         }
1014                         else if ((ntree->type == NTREE_COMPOSIT) &&
1015                                  ELEM(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB, CMP_NODE_HUECORRECT))
1016                         {
1017                                 write_curvemapping(wd, node->storage);
1018                         }
1019                         else if ((ntree->type == NTREE_TEXTURE) &&
1020                                  (node->type == TEX_NODE_CURVE_RGB || node->type == TEX_NODE_CURVE_TIME))
1021                         {
1022                                 write_curvemapping(wd, node->storage);
1023                         }
1024                         else if ((ntree->type == NTREE_COMPOSIT) &&
1025                                  (node->type == CMP_NODE_MOVIEDISTORTION))
1026                         {
1027                                 /* pass */
1028                         }
1029                         else {
1030                                 writestruct_id(wd, DATA, node->typeinfo->storagename, 1, node->storage);
1031                         }
1032                 }
1033
1034                 if (node->type == CMP_NODE_OUTPUT_FILE) {
1035                         /* inputs have own storage data */
1036                         for (sock = node->inputs.first; sock; sock = sock->next) {
1037                                 writestruct(wd, DATA, NodeImageMultiFileSocket, 1, sock->storage);
1038                         }
1039                 }
1040                 if (node->type == CMP_NODE_IMAGE) {
1041                         /* write extra socket info */
1042                         for (sock = node->outputs.first; sock; sock = sock->next) {
1043                                 writestruct(wd, DATA, NodeImageLayer, 1, sock->storage);
1044                         }
1045                 }
1046         }
1047
1048         for (link = ntree->links.first; link; link = link->next) {
1049                 writestruct(wd, DATA, bNodeLink, 1, link);
1050         }
1051
1052         for (sock = ntree->inputs.first; sock; sock = sock->next) {
1053                 write_node_socket_interface(wd, ntree, sock);
1054         }
1055         for (sock = ntree->outputs.first; sock; sock = sock->next) {
1056                 write_node_socket_interface(wd, ntree, sock);
1057         }
1058 }
1059
1060 /**
1061  * Take care using 'use_active_win', since we wont want the currently active window
1062  * to change which scene renders (currently only used for undo).
1063  */
1064 static void current_screen_compat(Main *mainvar, bScreen **r_screen, bool use_active_win)
1065 {
1066         wmWindowManager *wm;
1067         wmWindow *window = NULL;
1068
1069         /* find a global current screen in the first open window, to have
1070          * a reasonable default for reading in older versions */
1071         wm = mainvar->wm.first;
1072
1073         if (wm) {
1074                 if (use_active_win) {
1075                         /* write the active window into the file, needed for multi-window undo T43424 */
1076                         for (window = wm->windows.first; window; window = window->next) {
1077                                 if (window->active) {
1078                                         break;
1079                                 }
1080                         }
1081
1082                         /* fallback */
1083                         if (window == NULL) {
1084                                 window = wm->windows.first;
1085                         }
1086                 }
1087                 else {
1088                         window = wm->windows.first;
1089                 }
1090         }
1091
1092         *r_screen = (window) ? window->screen : NULL;
1093 }
1094
1095 typedef struct RenderInfo {
1096         int sfra;
1097         int efra;
1098         char scene_name[MAX_ID_NAME - 2];
1099 } RenderInfo;
1100
1101 /* was for historic render-deamon feature,
1102  * now write because it can be easily extracted without
1103  * reading the whole blend file */
1104 static void write_renderinfo(WriteData *wd, Main *mainvar)
1105 {
1106         bScreen *curscreen;
1107         Scene *sce, *curscene = NULL;
1108         RenderInfo data;
1109
1110         /* XXX in future, handle multiple windows with multiple screens? */
1111         current_screen_compat(mainvar, &curscreen, false);
1112         if (curscreen) {
1113                 curscene = curscreen->scene;
1114         }
1115
1116         for (sce = mainvar->scene.first; sce; sce = sce->id.next) {
1117                 if (sce->id.lib == NULL && (sce == curscene || (sce->r.scemode & R_BG_RENDER))) {
1118                         data.sfra = sce->r.sfra;
1119                         data.efra = sce->r.efra;
1120                         memset(data.scene_name, 0, sizeof(data.scene_name));
1121
1122                         BLI_strncpy(data.scene_name, sce->id.name + 2, sizeof(data.scene_name));
1123
1124                         writedata(wd, REND, sizeof(data), &data);
1125                 }
1126         }
1127 }
1128
1129 static void write_keymapitem(WriteData *wd, wmKeyMapItem *kmi)
1130 {
1131         writestruct(wd, DATA, wmKeyMapItem, 1, kmi);
1132         if (kmi->properties) {
1133                 IDP_WriteProperty(kmi->properties, wd);
1134         }
1135 }
1136
1137 static void write_userdef(WriteData *wd)
1138 {
1139         bTheme *btheme;
1140         wmKeyMap *keymap;
1141         wmKeyMapItem *kmi;
1142         wmKeyMapDiffItem *kmdi;
1143         bAddon *bext;
1144         bPathCompare *path_cmp;
1145         uiStyle *style;
1146
1147         writestruct(wd, USER, UserDef, 1, &U);
1148
1149         for (btheme = U.themes.first; btheme; btheme = btheme->next) {
1150                 writestruct(wd, DATA, bTheme, 1, btheme);
1151         }
1152
1153         for (keymap = U.user_keymaps.first; keymap; keymap = keymap->next) {
1154                 writestruct(wd, DATA, wmKeyMap, 1, keymap);
1155
1156                 for (kmdi = keymap->diff_items.first; kmdi; kmdi = kmdi->next) {
1157                         writestruct(wd, DATA, wmKeyMapDiffItem, 1, kmdi);
1158                         if (kmdi->remove_item) {
1159                                 write_keymapitem(wd, kmdi->remove_item);
1160                         }
1161                         if (kmdi->add_item) {
1162                                 write_keymapitem(wd, kmdi->add_item);
1163                         }
1164                 }
1165
1166                 for (kmi = keymap->items.first; kmi; kmi = kmi->next) {
1167                         write_keymapitem(wd, kmi);
1168                 }
1169         }
1170
1171         for (bext = U.addons.first; bext; bext = bext->next) {
1172                 writestruct(wd, DATA, bAddon, 1, bext);
1173                 if (bext->prop) {
1174                         IDP_WriteProperty(bext->prop, wd);
1175                 }
1176         }
1177
1178         for (path_cmp = U.autoexec_paths.first; path_cmp; path_cmp = path_cmp->next) {
1179                 writestruct(wd, DATA, bPathCompare, 1, path_cmp);
1180         }
1181
1182         for (style = U.uistyles.first; style; style = style->next) {
1183                 writestruct(wd, DATA, uiStyle, 1, style);
1184         }
1185 }
1186
1187 static void write_properties(WriteData *wd, ListBase *lb)
1188 {
1189         bProperty *prop;
1190
1191         prop = lb->first;
1192         while (prop) {
1193                 writestruct(wd, DATA, bProperty, 1, prop);
1194
1195                 if (prop->poin && prop->poin != &prop->data) {
1196                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
1197                 }
1198
1199                 prop = prop->next;
1200         }
1201 }
1202
1203 static void write_sensors(WriteData *wd, ListBase *lb)
1204 {
1205         bSensor *sens;
1206
1207         sens = lb->first;
1208         while (sens) {
1209                 writestruct(wd, DATA, bSensor, 1, sens);
1210
1211                 writedata(wd, DATA, sizeof(void *) * sens->totlinks, sens->links);
1212
1213                 switch (sens->type) {
1214                         case SENS_NEAR:
1215                                 writestruct(wd, DATA, bNearSensor, 1, sens->data);
1216                                 break;
1217                         case SENS_MOUSE:
1218                                 writestruct(wd, DATA, bMouseSensor, 1, sens->data);
1219                                 break;
1220                         case SENS_KEYBOARD:
1221                                 writestruct(wd, DATA, bKeyboardSensor, 1, sens->data);
1222                                 break;
1223                         case SENS_PROPERTY:
1224                                 writestruct(wd, DATA, bPropertySensor, 1, sens->data);
1225                                 break;
1226                         case SENS_ARMATURE:
1227                                 writestruct(wd, DATA, bArmatureSensor, 1, sens->data);
1228                                 break;
1229                         case SENS_ACTUATOR:
1230                                 writestruct(wd, DATA, bActuatorSensor, 1, sens->data);
1231                                 break;
1232                         case SENS_DELAY:
1233                                 writestruct(wd, DATA, bDelaySensor, 1, sens->data);
1234                                 break;
1235                         case SENS_COLLISION:
1236                                 writestruct(wd, DATA, bCollisionSensor, 1, sens->data);
1237                                 break;
1238                         case SENS_RADAR:
1239                                 writestruct(wd, DATA, bRadarSensor, 1, sens->data);
1240                                 break;
1241                         case SENS_RANDOM:
1242                                 writestruct(wd, DATA, bRandomSensor, 1, sens->data);
1243                                 break;
1244                         case SENS_RAY:
1245                                 writestruct(wd, DATA, bRaySensor, 1, sens->data);
1246                                 break;
1247                         case SENS_MESSAGE:
1248                                 writestruct(wd, DATA, bMessageSensor, 1, sens->data);
1249                                 break;
1250                         case SENS_JOYSTICK:
1251                                 writestruct(wd, DATA, bJoystickSensor, 1, sens->data);
1252                                 break;
1253                         default:
1254                                 ; /* error: don't know how to write this file */
1255                 }
1256
1257                 sens = sens->next;
1258         }
1259 }
1260
1261 static void write_controllers(WriteData *wd, ListBase *lb)
1262 {
1263         bController *cont;
1264
1265         cont = lb->first;
1266         while (cont) {
1267                 writestruct(wd, DATA, bController, 1, cont);
1268
1269                 writedata(wd, DATA, sizeof(void *) * cont->totlinks, cont->links);
1270
1271                 switch (cont->type) {
1272                         case CONT_EXPRESSION:
1273                                 writestruct(wd, DATA, bExpressionCont, 1, cont->data);
1274                                 break;
1275                         case CONT_PYTHON:
1276                                 writestruct(wd, DATA, bPythonCont, 1, cont->data);
1277                                 break;
1278                         default:
1279                                 ; /* error: don't know how to write this file */
1280                 }
1281
1282                 cont = cont->next;
1283         }
1284 }
1285
1286 static void write_actuators(WriteData *wd, ListBase *lb)
1287 {
1288         bActuator *act;
1289
1290         act = lb->first;
1291         while (act) {
1292                 writestruct(wd, DATA, bActuator, 1, act);
1293
1294                 switch (act->type) {
1295                         case ACT_ACTION:
1296                         case ACT_SHAPEACTION:
1297                                 writestruct(wd, DATA, bActionActuator, 1, act->data);
1298                                 break;
1299                         case ACT_SOUND:
1300                                 writestruct(wd, DATA, bSoundActuator, 1, act->data);
1301                                 break;
1302                         case ACT_OBJECT:
1303                                 writestruct(wd, DATA, bObjectActuator, 1, act->data);
1304                                 break;
1305                         case ACT_PROPERTY:
1306                                 writestruct(wd, DATA, bPropertyActuator, 1, act->data);
1307                                 break;
1308                         case ACT_CAMERA:
1309                                 writestruct(wd, DATA, bCameraActuator, 1, act->data);
1310                                 break;
1311                         case ACT_CONSTRAINT:
1312                                 writestruct(wd, DATA, bConstraintActuator, 1, act->data);
1313                                 break;
1314                         case ACT_EDIT_OBJECT:
1315                                 writestruct(wd, DATA, bEditObjectActuator, 1, act->data);
1316                                 break;
1317                         case ACT_SCENE:
1318                                 writestruct(wd, DATA, bSceneActuator, 1, act->data);
1319                                 break;
1320                         case ACT_GROUP:
1321                                 writestruct(wd, DATA, bGroupActuator, 1, act->data);
1322                                 break;
1323                         case ACT_RANDOM:
1324                                 writestruct(wd, DATA, bRandomActuator, 1, act->data);
1325                                 break;
1326                         case ACT_MESSAGE:
1327                                 writestruct(wd, DATA, bMessageActuator, 1, act->data);
1328                                 break;
1329                         case ACT_GAME:
1330                                 writestruct(wd, DATA, bGameActuator, 1, act->data);
1331                                 break;
1332                         case ACT_VISIBILITY:
1333                                 writestruct(wd, DATA, bVisibilityActuator, 1, act->data);
1334                                 break;
1335                         case ACT_2DFILTER:
1336                                 writestruct(wd, DATA, bTwoDFilterActuator, 1, act->data);
1337                                 break;
1338                         case ACT_PARENT:
1339                                 writestruct(wd, DATA, bParentActuator, 1, act->data);
1340                                 break;
1341                         case ACT_STATE:
1342                                 writestruct(wd, DATA, bStateActuator, 1, act->data);
1343                                 break;
1344                         case ACT_ARMATURE:
1345                                 writestruct(wd, DATA, bArmatureActuator, 1, act->data);
1346                                 break;
1347                         case ACT_STEERING:
1348                                 writestruct(wd, DATA, bSteeringActuator, 1, act->data);
1349                                 break;
1350                         case ACT_MOUSE:
1351                                 writestruct(wd, DATA, bMouseActuator, 1, act->data);
1352                                 break;
1353                         default:
1354                                 ; /* error: don't know how to write this file */
1355                 }
1356
1357                 act = act->next;
1358         }
1359 }
1360
1361 static void write_motionpath(WriteData *wd, bMotionPath *mpath)
1362 {
1363         /* sanity checks */
1364         if (mpath == NULL) {
1365                 return;
1366         }
1367
1368         /* firstly, just write the motionpath struct */
1369         writestruct(wd, DATA, bMotionPath, 1, mpath);
1370
1371         /* now write the array of data */
1372         writestruct(wd, DATA, bMotionPathVert, mpath->length, mpath->points);
1373 }
1374
1375 static void write_constraints(WriteData *wd, ListBase *conlist)
1376 {
1377         bConstraint *con;
1378
1379         for (con = conlist->first; con; con = con->next) {
1380                 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
1381
1382                 /* Write the specific data */
1383                 if (cti && con->data) {
1384                         /* firstly, just write the plain con->data struct */
1385                         writestruct_id(wd, DATA, cti->structName, 1, con->data);
1386
1387                         /* do any constraint specific stuff */
1388                         switch (con->type) {
1389                                 case CONSTRAINT_TYPE_PYTHON:
1390                                 {
1391                                         bPythonConstraint *data = con->data;
1392                                         bConstraintTarget *ct;
1393
1394                                         /* write targets */
1395                                         for (ct = data->targets.first; ct; ct = ct->next) {
1396                                                 writestruct(wd, DATA, bConstraintTarget, 1, ct);
1397                                         }
1398
1399                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1400                                          * of library blocks that implement this.*/
1401                                         IDP_WriteProperty(data->prop, wd);
1402
1403                                         break;
1404                                 }
1405                                 case CONSTRAINT_TYPE_SPLINEIK:
1406                                 {
1407                                         bSplineIKConstraint *data = con->data;
1408
1409                                         /* write points array */
1410                                         writedata(wd, DATA, sizeof(float) * (data->numpoints), data->points);
1411
1412                                         break;
1413                                 }
1414                         }
1415                 }
1416
1417                 /* Write the constraint */
1418                 writestruct(wd, DATA, bConstraint, 1, con);
1419         }
1420 }
1421
1422 static void write_pose(WriteData *wd, bPose *pose)
1423 {
1424         bPoseChannel *chan;
1425         bActionGroup *grp;
1426
1427         /* Write each channel */
1428         if (pose == NULL) {
1429                 return;
1430         }
1431
1432         /* Write channels */
1433         for (chan = pose->chanbase.first; chan; chan = chan->next) {
1434                 /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1435                  * of library blocks that implement this.*/
1436                 if (chan->prop) {
1437                         IDP_WriteProperty(chan->prop, wd);
1438                 }
1439
1440                 write_constraints(wd, &chan->constraints);
1441
1442                 write_motionpath(wd, chan->mpath);
1443
1444                 /* prevent crashes with autosave,
1445                  * when a bone duplicated in editmode has not yet been assigned to its posechannel */
1446                 if (chan->bone) {
1447                         /* gets restored on read, for library armatures */
1448                         chan->selectflag = chan->bone->flag & BONE_SELECTED;
1449                 }
1450
1451                 writestruct(wd, DATA, bPoseChannel, 1, chan);
1452         }
1453
1454         /* Write groups */
1455         for (grp = pose->agroups.first; grp; grp = grp->next) {
1456                 writestruct(wd, DATA, bActionGroup, 1, grp);
1457         }
1458
1459         /* write IK param */
1460         if (pose->ikparam) {
1461                 const char *structname = BKE_pose_ikparam_get_name(pose);
1462                 if (structname) {
1463                         writestruct_id(wd, DATA, structname, 1, pose->ikparam);
1464                 }
1465         }
1466
1467         /* Write this pose */
1468         writestruct(wd, DATA, bPose, 1, pose);
1469
1470 }
1471
1472 static void write_defgroups(WriteData *wd, ListBase *defbase)
1473 {
1474         for (bDeformGroup *defgroup = defbase->first; defgroup; defgroup = defgroup->next) {
1475                 writestruct(wd, DATA, bDeformGroup, 1, defgroup);
1476         }
1477 }
1478
1479 static void write_modifiers(WriteData *wd, ListBase *modbase)
1480 {
1481         ModifierData *md;
1482
1483         if (modbase == NULL) {
1484                 return;
1485         }
1486
1487         for (md = modbase->first; md; md = md->next) {
1488                 const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1489                 if (mti == NULL) {
1490                         return;
1491                 }
1492
1493                 writestruct_id(wd, DATA, mti->structName, 1, md);
1494
1495                 if (md->type == eModifierType_Hook) {
1496                         HookModifierData *hmd = (HookModifierData *)md;
1497
1498                         if (hmd->curfalloff) {
1499                                 write_curvemapping(wd, hmd->curfalloff);
1500                         }
1501
1502                         writedata(wd, DATA, sizeof(int) * hmd->totindex, hmd->indexar);
1503                 }
1504                 else if (md->type == eModifierType_Cloth) {
1505                         ClothModifierData *clmd = (ClothModifierData *)md;
1506
1507                         writestruct(wd, DATA, ClothSimSettings, 1, clmd->sim_parms);
1508                         writestruct(wd, DATA, ClothCollSettings, 1, clmd->coll_parms);
1509                         writestruct(wd, DATA, EffectorWeights, 1, clmd->sim_parms->effector_weights);
1510                 }
1511                 else if (md->type == eModifierType_Smoke) {
1512                         SmokeModifierData *smd = (SmokeModifierData *)md;
1513
1514                         if (smd->type & MOD_SMOKE_TYPE_DOMAIN) {
1515                                 writestruct(wd, DATA, SmokeDomainSettings, 1, smd->domain);
1516
1517                                 if (smd->domain) {
1518                                         writestruct(wd, DATA, EffectorWeights, 1, smd->domain->effector_weights);
1519                                 }
1520                         }
1521                         else if (smd->type & MOD_SMOKE_TYPE_FLOW) {
1522                                 writestruct(wd, DATA, SmokeFlowSettings, 1, smd->flow);
1523                         }
1524                         else if (smd->type & MOD_SMOKE_TYPE_COLL) {
1525                                 writestruct(wd, DATA, SmokeCollSettings, 1, smd->coll);
1526                         }
1527                 }
1528                 else if (md->type == eModifierType_Fluidsim) {
1529                         FluidsimModifierData *fluidmd = (FluidsimModifierData *)md;
1530
1531                         writestruct(wd, DATA, FluidsimSettings, 1, fluidmd->fss);
1532                 }
1533                 else if (md->type == eModifierType_DynamicPaint) {
1534                         DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md;
1535
1536                         if (pmd->canvas) {
1537                                 DynamicPaintSurface *surface;
1538                                 writestruct(wd, DATA, DynamicPaintCanvasSettings, 1, pmd->canvas);
1539
1540                                 /* write surfaces */
1541                                 for (surface = pmd->canvas->surfaces.first; surface; surface = surface->next) {
1542                                         writestruct(wd, DATA, DynamicPaintSurface, 1, surface);
1543                                 }
1544                                 /* write caches and effector weights */
1545                                 for (surface = pmd->canvas->surfaces.first; surface; surface = surface->next) {
1546                                         writestruct(wd, DATA, EffectorWeights, 1, surface->effector_weights);
1547                                 }
1548                         }
1549                         if (pmd->brush) {
1550                                 writestruct(wd, DATA, DynamicPaintBrushSettings, 1, pmd->brush);
1551                                 writestruct(wd, DATA, ColorBand, 1, pmd->brush->paint_ramp);
1552                                 writestruct(wd, DATA, ColorBand, 1, pmd->brush->vel_ramp);
1553                         }
1554                 }
1555                 else if (md->type == eModifierType_Collision) {
1556
1557 #if 0
1558                         CollisionModifierData *collmd = (CollisionModifierData *)md;
1559                         // TODO: CollisionModifier should use pointcache
1560                         // + have proper reset events before enabling this
1561                         writestruct(wd, DATA, MVert, collmd->numverts, collmd->x);
1562                         writestruct(wd, DATA, MVert, collmd->numverts, collmd->xnew);
1563                         writestruct(wd, DATA, MFace, collmd->numfaces, collmd->mfaces);
1564 #endif
1565                 }
1566                 else if (md->type == eModifierType_MeshDeform) {
1567                         MeshDeformModifierData *mmd = (MeshDeformModifierData *)md;
1568                         int size = mmd->dyngridsize;
1569
1570                         writestruct(wd, DATA, MDefInfluence, mmd->totinfluence, mmd->bindinfluences);
1571                         writedata(wd, DATA, sizeof(int) * (mmd->totvert + 1), mmd->bindoffsets);
1572                         writedata(wd, DATA, sizeof(float) * 3 * mmd->totcagevert,
1573                                   mmd->bindcagecos);
1574                         writestruct(wd, DATA, MDefCell, size * size * size, mmd->dyngrid);
1575                         writestruct(wd, DATA, MDefInfluence, mmd->totinfluence, mmd->dyninfluences);
1576                         writedata(wd, DATA, sizeof(int) * mmd->totvert, mmd->dynverts);
1577                 }
1578                 else if (md->type == eModifierType_Warp) {
1579                         WarpModifierData *tmd = (WarpModifierData *)md;
1580                         if (tmd->curfalloff) {
1581                                 write_curvemapping(wd, tmd->curfalloff);
1582                         }
1583                 }
1584                 else if (md->type == eModifierType_WeightVGEdit) {
1585                         WeightVGEditModifierData *wmd = (WeightVGEditModifierData *)md;
1586
1587                         if (wmd->cmap_curve) {
1588                                 write_curvemapping(wd, wmd->cmap_curve);
1589                         }
1590                 }
1591                 else if (md->type == eModifierType_LaplacianDeform) {
1592                         LaplacianDeformModifierData *lmd = (LaplacianDeformModifierData *)md;
1593
1594                         writedata(wd, DATA, sizeof(float) * lmd->total_verts * 3, lmd->vertexco);
1595                 }
1596                 else if (md->type == eModifierType_CorrectiveSmooth) {
1597                         CorrectiveSmoothModifierData *csmd = (CorrectiveSmoothModifierData *)md;
1598
1599                         if (csmd->bind_coords) {
1600                                 writedata(wd, DATA, sizeof(float[3]) * csmd->bind_coords_num, csmd->bind_coords);
1601                         }
1602                 }
1603         }
1604 }
1605
1606 static void write_objects(WriteData *wd, ListBase *idbase)
1607 {
1608         Object *ob;
1609
1610         ob = idbase->first;
1611         while (ob) {
1612                 if (ob->id.us > 0 || wd->current) {
1613                         /* write LibData */
1614                         writestruct(wd, ID_OB, Object, 1, ob);
1615                         write_iddata(wd, &ob->id);
1616
1617                         if (ob->adt) {
1618                                 write_animdata(wd, ob->adt);
1619                         }
1620
1621                         /* direct data */
1622                         writedata(wd, DATA, sizeof(void *) * ob->totcol, ob->mat);
1623                         writedata(wd, DATA, sizeof(char) * ob->totcol, ob->matbits);
1624                         /* write_effects(wd, &ob->effect); */ /* not used anymore */
1625                         write_properties(wd, &ob->prop);
1626                         write_sensors(wd, &ob->sensors);
1627                         write_controllers(wd, &ob->controllers);
1628                         write_actuators(wd, &ob->actuators);
1629
1630                         if (ob->type == OB_ARMATURE) {
1631                                 bArmature *arm = ob->data;
1632                                 if (arm && ob->pose && arm->act_bone) {
1633                                         BLI_strncpy(ob->pose->proxy_act_bone, arm->act_bone->name, sizeof(ob->pose->proxy_act_bone));
1634                                 }
1635                         }
1636
1637                         write_pose(wd, ob->pose);
1638                         write_defgroups(wd, &ob->defbase);
1639                         write_constraints(wd, &ob->constraints);
1640                         write_motionpath(wd, ob->mpath);
1641
1642                         writestruct(wd, DATA, PartDeflect, 1, ob->pd);
1643                         writestruct(wd, DATA, SoftBody, 1, ob->soft);
1644                         if (ob->soft) {
1645                                 writestruct(wd, DATA, EffectorWeights, 1, ob->soft->effector_weights);
1646                         }
1647                         writestruct(wd, DATA, BulletSoftBody, 1, ob->bsoft);
1648
1649                         if (ob->rigidbody_object) {
1650                                 /* TODO: if any extra data is added to handle duplis, will need separate function then */
1651                                 writestruct(wd, DATA, RigidBodyOb, 1, ob->rigidbody_object);
1652                         }
1653                         if (ob->rigidbody_constraint) {
1654                                 writestruct(wd, DATA, RigidBodyCon, 1, ob->rigidbody_constraint);
1655                         }
1656
1657                         if (ob->type == OB_EMPTY && ob->empty_drawtype == OB_EMPTY_IMAGE) {
1658                                 writestruct(wd, DATA, ImageUser, 1, ob->iuser);
1659                         }
1660
1661                         write_modifiers(wd, &ob->modifiers);
1662
1663                         writelist(wd, DATA, LinkData, &ob->pc_ids);
1664                         writelist(wd, DATA, LodLevel, &ob->lodlevels);
1665                 }
1666
1667                 write_previews(wd, ob->preview);
1668
1669                 ob = ob->id.next;
1670         }
1671
1672         mywrite_flush(wd);
1673 }
1674
1675
1676 static void write_vfonts(WriteData *wd, ListBase *idbase)
1677 {
1678         VFont *vf;
1679         PackedFile *pf;
1680
1681         vf = idbase->first;
1682         while (vf) {
1683                 if (vf->id.us > 0 || wd->current) {
1684                         /* write LibData */
1685                         writestruct(wd, ID_VF, VFont, 1, vf);
1686                         write_iddata(wd, &vf->id);
1687
1688                         /* direct data */
1689
1690                         if (vf->packedfile) {
1691                                 pf = vf->packedfile;
1692                                 writestruct(wd, DATA, PackedFile, 1, pf);
1693                                 writedata(wd, DATA, pf->size, pf->data);
1694                         }
1695                 }
1696
1697                 vf = vf->id.next;
1698         }
1699
1700         mywrite_flush(wd);
1701 }
1702
1703
1704 static void write_keys(WriteData *wd, ListBase *idbase)
1705 {
1706         Key *key;
1707         KeyBlock *kb;
1708
1709         key = idbase->first;
1710         while (key) {
1711                 if (key->id.us > 0 || wd->current) {
1712                         /* write LibData */
1713                         writestruct(wd, ID_KE, Key, 1, key);
1714                         write_iddata(wd, &key->id);
1715
1716                         if (key->adt) {
1717                                 write_animdata(wd, key->adt);
1718                         }
1719
1720                         /* direct data */
1721                         kb = key->block.first;
1722                         while (kb) {
1723                                 writestruct(wd, DATA, KeyBlock, 1, kb);
1724                                 if (kb->data) {
1725                                         writedata(wd, DATA, kb->totelem * key->elemsize, kb->data);
1726                                 }
1727                                 kb = kb->next;
1728                         }
1729                 }
1730
1731                 key = key->id.next;
1732         }
1733
1734         mywrite_flush(wd);
1735 }
1736
1737 static void write_cameras(WriteData *wd, ListBase *idbase)
1738 {
1739         Camera *cam;
1740
1741         cam = idbase->first;
1742         while (cam) {
1743                 if (cam->id.us > 0 || wd->current) {
1744                         /* write LibData */
1745                         writestruct(wd, ID_CA, Camera, 1, cam);
1746                         write_iddata(wd, &cam->id);
1747
1748                         if (cam->adt) {
1749                                 write_animdata(wd, cam->adt);
1750                         }
1751                 }
1752
1753                 cam = cam->id.next;
1754         }
1755 }
1756
1757 static void write_mballs(WriteData *wd, ListBase *idbase)
1758 {
1759         MetaBall *mb;
1760         MetaElem *ml;
1761
1762         mb = idbase->first;
1763         while (mb) {
1764                 if (mb->id.us > 0 || wd->current) {
1765                         /* write LibData */
1766                         writestruct(wd, ID_MB, MetaBall, 1, mb);
1767                         write_iddata(wd, &mb->id);
1768
1769                         /* direct data */
1770                         writedata(wd, DATA, sizeof(void *) * mb->totcol, mb->mat);
1771                         if (mb->adt) {
1772                                 write_animdata(wd, mb->adt);
1773                         }
1774
1775                         ml = mb->elems.first;
1776                         while (ml) {
1777                                 writestruct(wd, DATA, MetaElem, 1, ml);
1778                                 ml = ml->next;
1779                         }
1780                 }
1781                 mb = mb->id.next;
1782         }
1783 }
1784
1785 static void write_curves(WriteData *wd, ListBase *idbase)
1786 {
1787         Curve *cu;
1788         Nurb *nu;
1789
1790         cu = idbase->first;
1791         while (cu) {
1792                 if (cu->id.us > 0 || wd->current) {
1793                         /* write LibData */
1794                         writestruct(wd, ID_CU, Curve, 1, cu);
1795                         write_iddata(wd, &cu->id);
1796
1797                         /* direct data */
1798                         writedata(wd, DATA, sizeof(void *) * cu->totcol, cu->mat);
1799                         if (cu->adt) {
1800                                 write_animdata(wd, cu->adt);
1801                         }
1802
1803                         if (cu->vfont) {
1804                                 writedata(wd, DATA, cu->len + 1, cu->str);
1805                                 writestruct(wd, DATA, CharInfo, cu->len_wchar + 1, cu->strinfo);
1806                                 writestruct(wd, DATA, TextBox, cu->totbox, cu->tb);
1807                         }
1808                         else {
1809                                 /* is also the order of reading */
1810                                 nu = cu->nurb.first;
1811                                 while (nu) {
1812                                         writestruct(wd, DATA, Nurb, 1, nu);
1813                                         nu = nu->next;
1814                                 }
1815                                 nu = cu->nurb.first;
1816                                 while (nu) {
1817                                         if (nu->type == CU_BEZIER) {
1818                                                 writestruct(wd, DATA, BezTriple, nu->pntsu, nu->bezt);
1819                                         }
1820                                         else {
1821                                                 writestruct(wd, DATA, BPoint, nu->pntsu * nu->pntsv, nu->bp);
1822                                                 if (nu->knotsu) {
1823                                                         writedata(wd, DATA, KNOTSU(nu) * sizeof(float), nu->knotsu);
1824                                                 }
1825                                                 if (nu->knotsv) {
1826                                                         writedata(wd, DATA, KNOTSV(nu) * sizeof(float), nu->knotsv);
1827                                                 }
1828                                         }
1829                                         nu = nu->next;
1830                                 }
1831                         }
1832                 }
1833                 cu = cu->id.next;
1834         }
1835
1836         mywrite_flush(wd);
1837 }
1838
1839 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1840 {
1841         if (dvlist) {
1842
1843                 /* Write the dvert list */
1844                 writestruct(wd, DATA, MDeformVert, count, dvlist);
1845
1846                 /* Write deformation data for each dvert */
1847                 for (int i = 0; i < count; i++) {
1848                         if (dvlist[i].dw) {
1849                                 writestruct(wd, DATA, MDeformWeight, dvlist[i].totweight, dvlist[i].dw);
1850                         }
1851                 }
1852         }
1853 }
1854
1855 static void write_mdisps(WriteData *wd, int count, MDisps *mdlist, int external)
1856 {
1857         if (mdlist) {
1858                 int i;
1859
1860                 writestruct(wd, DATA, MDisps, count, mdlist);
1861                 for (i = 0; i < count; ++i) {
1862                         MDisps *md = &mdlist[i];
1863                         if (md->disps) {
1864                                 if (!external) {
1865                                         writedata(wd, DATA, sizeof(float) * 3 * md->totdisp, md->disps);
1866                                 }
1867                         }
1868
1869                         if (md->hidden) {
1870                                 writedata(wd, DATA, BLI_BITMAP_SIZE(md->totdisp), md->hidden);
1871                         }
1872                 }
1873         }
1874 }
1875
1876 static void write_grid_paint_mask(WriteData *wd, int count, GridPaintMask *grid_paint_mask)
1877 {
1878         if (grid_paint_mask) {
1879                 int i;
1880
1881                 writestruct(wd, DATA, GridPaintMask, count, grid_paint_mask);
1882                 for (i = 0; i < count; ++i) {
1883                         GridPaintMask *gpm = &grid_paint_mask[i];
1884                         if (gpm->data) {
1885                                 const int gridsize = BKE_ccg_gridsize(gpm->level);
1886                                 writedata(wd, DATA,
1887                                           sizeof(*gpm->data) * gridsize * gridsize,
1888                                           gpm->data);
1889                         }
1890                 }
1891         }
1892 }
1893
1894 static void write_customdata(
1895         WriteData *wd, ID *id, int count, CustomData *data, CustomDataLayer *layers,
1896         int partial_type, int partial_count)
1897 {
1898         int i;
1899
1900         /* write external customdata (not for undo) */
1901         if (data->external && !wd->current) {
1902                 CustomData_external_write(data, id, CD_MASK_MESH, count, 0);
1903         }
1904
1905         writestruct_at_address(wd, DATA, CustomDataLayer, data->totlayer, data->layers, layers);
1906
1907         for (i = 0; i < data->totlayer; i++) {
1908                 CustomDataLayer *layer = &layers[i];
1909                 const char *structname;
1910                 int structnum, datasize;
1911
1912                 if (layer->type == CD_MDEFORMVERT) {
1913                         /* layer types that allocate own memory need special handling */
1914                         write_dverts(wd, count, layer->data);
1915                 }
1916                 else if (layer->type == CD_MDISPS) {
1917                         write_mdisps(wd, count, layer->data, layer->flag & CD_FLAG_EXTERNAL);
1918                 }
1919                 else if (layer->type == CD_PAINT_MASK) {
1920                         const float *layer_data = layer->data;
1921                         writedata(wd, DATA, sizeof(*layer_data) * count, layer_data);
1922                 }
1923                 else if (layer->type == CD_GRID_PAINT_MASK) {
1924                         write_grid_paint_mask(wd, count, layer->data);
1925                 }
1926                 else {
1927                         CustomData_file_write_info(layer->type, &structname, &structnum);
1928                         if (structnum) {
1929                                 /* when using partial visibility, the MEdge and MFace layers
1930                                  * are smaller than the original, so their type and count is
1931                                  * passed to make this work */
1932                                 if (layer->type != partial_type) {
1933                                         datasize = structnum * count;
1934                                 }
1935                                 else {
1936                                         datasize = structnum * partial_count;
1937                                 }
1938
1939                                 writestruct_id(wd, DATA, structname, datasize, layer->data);
1940                         }
1941                         else {
1942                                 printf("%s error: layer '%s':%d - can't be written to file\n",
1943                                        __func__, structname, layer->type);
1944                         }
1945                 }
1946         }
1947
1948         if (data->external) {
1949                 writestruct(wd, DATA, CustomDataExternal, 1, data->external);
1950         }
1951 }
1952
1953 static void write_meshes(WriteData *wd, ListBase *idbase)
1954 {
1955         Mesh *mesh;
1956         bool save_for_old_blender = false;
1957
1958 #ifdef USE_BMESH_SAVE_AS_COMPAT
1959         save_for_old_blender = wd->use_mesh_compat; /* option to save with older mesh format */
1960 #endif
1961
1962         mesh = idbase->first;
1963         while (mesh) {
1964                 CustomDataLayer *vlayers = NULL, vlayers_buff[CD_TEMP_CHUNK_SIZE];
1965                 CustomDataLayer *elayers = NULL, elayers_buff[CD_TEMP_CHUNK_SIZE];
1966                 CustomDataLayer *flayers = NULL, flayers_buff[CD_TEMP_CHUNK_SIZE];
1967                 CustomDataLayer *llayers = NULL, llayers_buff[CD_TEMP_CHUNK_SIZE];
1968                 CustomDataLayer *players = NULL, players_buff[CD_TEMP_CHUNK_SIZE];
1969
1970                 if (mesh->id.us > 0 || wd->current) {
1971                         /* write LibData */
1972                         if (!save_for_old_blender) {
1973                                 /* write a copy of the mesh, don't modify in place because it is
1974                                  * not thread safe for threaded renders that are reading this */
1975                                 Mesh *old_mesh = mesh;
1976                                 Mesh copy_mesh = *mesh;
1977                                 mesh = &copy_mesh;
1978
1979 #ifdef USE_BMESH_SAVE_WITHOUT_MFACE
1980                                 /* cache only - don't write */
1981                                 mesh->mface = NULL;
1982                                 mesh->totface = 0;
1983                                 memset(&mesh->fdata, 0, sizeof(mesh->fdata));
1984 #endif /* USE_BMESH_SAVE_WITHOUT_MFACE */
1985
1986                                 /**
1987                                  * Those calls:
1988                                  *   - Reduce mesh->xdata.totlayer to number of layers to write.
1989                                  *   - Fill xlayers with those layers to be written.
1990                                  * Note that mesh->xdata is from now on invalid for Blender, but this is why the whole mesh is
1991                                  * a temp local copy!
1992                                  */
1993                                 CustomData_file_write_prepare(&mesh->vdata, &vlayers, vlayers_buff, ARRAY_SIZE(vlayers_buff));
1994                                 CustomData_file_write_prepare(&mesh->edata, &elayers, elayers_buff, ARRAY_SIZE(elayers_buff));
1995 #ifndef USE_BMESH_SAVE_WITHOUT_MFACE  /* Do not copy org fdata in this case!!! */
1996                                 CustomData_file_write_prepare(&mesh->fdata, &flayers, flayers_buff, ARRAY_SIZE(flayers_buff));
1997 #else
1998                                 flayers = flayers_buff;
1999 #endif
2000                                 CustomData_file_write_prepare(&mesh->ldata, &llayers, llayers_buff, ARRAY_SIZE(llayers_buff));
2001                                 CustomData_file_write_prepare(&mesh->pdata, &players, players_buff, ARRAY_SIZE(players_buff));
2002
2003                                 writestruct_at_address(wd, ID_ME, Mesh, 1, old_mesh, mesh);
2004                                 write_iddata(wd, &mesh->id);
2005
2006                                 /* direct data */
2007                                 if (mesh->adt) {
2008                                         write_animdata(wd, mesh->adt);
2009                                 }
2010
2011                                 writedata(wd, DATA, sizeof(void *) * mesh->totcol, mesh->mat);
2012                                 writedata(wd, DATA, sizeof(MSelect) * mesh->totselect, mesh->mselect);
2013
2014                                 write_customdata(wd, &mesh->id, mesh->totvert, &mesh->vdata, vlayers, -1, 0);
2015                                 write_customdata(wd, &mesh->id, mesh->totedge, &mesh->edata, elayers, -1, 0);
2016                                 /* fdata is really a dummy - written so slots align */
2017                                 write_customdata(wd, &mesh->id, mesh->totface, &mesh->fdata, flayers, -1, 0);
2018                                 write_customdata(wd, &mesh->id, mesh->totloop, &mesh->ldata, llayers, -1, 0);
2019                                 write_customdata(wd, &mesh->id, mesh->totpoly, &mesh->pdata, players, -1, 0);
2020
2021                                 /* restore pointer */
2022                                 mesh = old_mesh;
2023                         }
2024                         else {
2025
2026 #ifdef USE_BMESH_SAVE_AS_COMPAT
2027                                 /* write a copy of the mesh, don't modify in place because it is
2028                                  * not thread safe for threaded renders that are reading this */
2029                                 Mesh *old_mesh = mesh;
2030                                 Mesh copy_mesh = *mesh;
2031                                 mesh = &copy_mesh;
2032
2033                                 mesh->mpoly = NULL;
2034                                 mesh->mface = NULL;
2035                                 mesh->totface = 0;
2036                                 mesh->totpoly = 0;
2037                                 mesh->totloop = 0;
2038                                 CustomData_reset(&mesh->fdata);
2039                                 CustomData_reset(&mesh->pdata);
2040                                 CustomData_reset(&mesh->ldata);
2041                                 mesh->edit_btmesh = NULL;
2042
2043                                 /* now fill in polys to mfaces */
2044                                 /* XXX This breaks writing design, by using temp allocated memory, which will likely generate
2045                                  *     duplicates in stored 'old' addresses.
2046                                  *     This is very bad, but do not see easy way to avoid this, aside from generating those data
2047                                  *     outside of save process itself.
2048                                  *     Maybe we can live with this, though?
2049                                  */
2050                                 mesh->totface = BKE_mesh_mpoly_to_mface(&mesh->fdata, &old_mesh->ldata, &old_mesh->pdata,
2051                                                                         mesh->totface, old_mesh->totloop, old_mesh->totpoly);
2052
2053                                 BKE_mesh_update_customdata_pointers(mesh, false);
2054
2055                                 CustomData_file_write_prepare(&mesh->vdata, &vlayers, vlayers_buff, ARRAY_SIZE(vlayers_buff));
2056                                 CustomData_file_write_prepare(&mesh->edata, &elayers, elayers_buff, ARRAY_SIZE(elayers_buff));
2057                                 CustomData_file_write_prepare(&mesh->fdata, &flayers, flayers_buff, ARRAY_SIZE(flayers_buff));
2058 #if 0
2059                                 CustomData_file_write_prepare(&mesh->ldata, &llayers, llayers_buff, ARRAY_SIZE(llayers_buff));
2060                                 CustomData_file_write_prepare(&mesh->pdata, &players, players_buff, ARRAY_SIZE(players_buff));
2061 #endif
2062
2063                                 writestruct_at_address(wd, ID_ME, Mesh, 1, old_mesh, mesh);
2064                                 write_iddata(wd, &mesh->id);
2065
2066                                 /* direct data */
2067                                 if (mesh->adt) {
2068                                         write_animdata(wd, mesh->adt);
2069                                 }
2070
2071                                 writedata(wd, DATA, sizeof(void *) * mesh->totcol, mesh->mat);
2072                                 /* writedata(wd, DATA, sizeof(MSelect) * mesh->totselect, mesh->mselect); */ /* pre-bmesh NULL's */
2073
2074                                 write_customdata(wd, &mesh->id, mesh->totvert, &mesh->vdata, vlayers, -1, 0);
2075                                 write_customdata(wd, &mesh->id, mesh->totedge, &mesh->edata, elayers, -1, 0);
2076                                 write_customdata(wd, &mesh->id, mesh->totface, &mesh->fdata, flayers, -1, 0);
2077                                 /* harmless for older blender versioins but _not_ writing these keeps file size down */
2078 #if 0
2079                                 write_customdata(wd, &mesh->id, mesh->totloop, &mesh->ldata, llayers, -1, 0);
2080                                 write_customdata(wd, &mesh->id, mesh->totpoly, &mesh->pdata, players, -1, 0);
2081 #endif
2082
2083                                 CustomData_free(&mesh->fdata, mesh->totface);
2084                                 flayers = NULL;
2085
2086                                 /* restore pointer */
2087                                 mesh = old_mesh;
2088 #endif /* USE_BMESH_SAVE_AS_COMPAT */
2089                         }
2090                 }
2091
2092                 if (vlayers && vlayers != vlayers_buff) {
2093                         MEM_freeN(vlayers);
2094                 }
2095                 if (elayers && elayers != elayers_buff) {
2096                         MEM_freeN(elayers);
2097                 }
2098                 if (flayers && flayers != flayers_buff) {
2099                         MEM_freeN(flayers);
2100                 }
2101                 if (llayers && llayers != llayers_buff) {
2102                         MEM_freeN(llayers);
2103                 }
2104                 if (players && players != players_buff) {
2105                         MEM_freeN(players);
2106                 }
2107
2108                 mesh = mesh->id.next;
2109         }
2110
2111         mywrite_flush(wd);
2112 }
2113
2114 static void write_lattices(WriteData *wd, ListBase *idbase)
2115 {
2116         Lattice *lt;
2117
2118         lt = idbase->first;
2119         while (lt) {
2120                 if (lt->id.us > 0 || wd->current) {
2121                         /* write LibData */
2122                         writestruct(wd, ID_LT, Lattice, 1, lt);
2123                         write_iddata(wd, &lt->id);
2124
2125                         /* write animdata */
2126                         if (lt->adt) {
2127                                 write_animdata(wd, lt->adt);
2128                         }
2129
2130                         /* direct data */
2131                         writestruct(wd, DATA, BPoint, lt->pntsu * lt->pntsv * lt->pntsw, lt->def);
2132
2133                         write_dverts(wd, lt->pntsu * lt->pntsv * lt->pntsw, lt->dvert);
2134
2135                 }
2136                 lt = lt->id.next;
2137         }
2138
2139         mywrite_flush(wd);
2140 }
2141
2142 static void write_images(WriteData *wd, ListBase *idbase)
2143 {
2144         Image *ima;
2145         PackedFile *pf;
2146         ImageView *iv;
2147         ImagePackedFile *imapf;
2148
2149         ima = idbase->first;
2150         while (ima) {
2151                 if (ima->id.us > 0 || wd->current) {
2152                         /* Some trickery to keep forward compatibility of packed images. */
2153                         BLI_assert(ima->packedfile == NULL);
2154                         if (ima->packedfiles.first != NULL) {
2155                                 imapf = ima->packedfiles.first;
2156                                 ima->packedfile = imapf->packedfile;
2157                         }
2158
2159                         /* write LibData */
2160                         writestruct(wd, ID_IM, Image, 1, ima);
2161                         write_iddata(wd, &ima->id);
2162
2163                         for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next) {
2164                                 writestruct(wd, DATA, ImagePackedFile, 1, imapf);
2165                                 if (imapf->packedfile) {
2166                                         pf = imapf->packedfile;
2167                                         writestruct(wd, DATA, PackedFile, 1, pf);
2168                                         writedata(wd, DATA, pf->size, pf->data);
2169                                 }
2170                         }
2171
2172                         write_previews(wd, ima->preview);
2173
2174                         for (iv = ima->views.first; iv; iv = iv->next) {
2175                                 writestruct(wd, DATA, ImageView, 1, iv);
2176                         }
2177                         writestruct(wd, DATA, Stereo3dFormat, 1, ima->stereo3d_format);
2178
2179                         ima->packedfile = NULL;
2180                 }
2181                 ima = ima->id.next;
2182         }
2183
2184         mywrite_flush(wd);
2185 }
2186
2187 static void write_textures(WriteData *wd, ListBase *idbase)
2188 {
2189         Tex *tex;
2190
2191         tex = idbase->first;
2192         while (tex) {
2193                 if (tex->id.us > 0 || wd->current) {
2194                         /* write LibData */
2195                         writestruct(wd, ID_TE, Tex, 1, tex);
2196                         write_iddata(wd, &tex->id);
2197
2198                         if (tex->adt) {
2199                                 write_animdata(wd, tex->adt);
2200                         }
2201
2202                         /* direct data */
2203                         if (tex->coba) {
2204                                 writestruct(wd, DATA, ColorBand, 1, tex->coba);
2205                         }
2206                         if (tex->type == TEX_ENVMAP && tex->env) {
2207                                 writestruct(wd, DATA, EnvMap, 1, tex->env);
2208                         }
2209                         if (tex->type == TEX_POINTDENSITY && tex->pd) {
2210                                 writestruct(wd, DATA, PointDensity, 1, tex->pd);
2211                                 if (tex->pd->coba) {
2212                                         writestruct(wd, DATA, ColorBand, 1, tex->pd->coba);
2213                                 }
2214                                 if (tex->pd->falloff_curve) {
2215                                         write_curvemapping(wd, tex->pd->falloff_curve);
2216                                 }
2217                         }
2218                         if (tex->type == TEX_VOXELDATA) {
2219                                 writestruct(wd, DATA, VoxelData, 1, tex->vd);
2220                         }
2221                         if (tex->type == TEX_OCEAN && tex->ot) {
2222                                 writestruct(wd, DATA, OceanTex, 1, tex->ot);
2223                         }
2224
2225                         /* nodetree is integral part of texture, no libdata */
2226                         if (tex->nodetree) {
2227                                 writestruct(wd, DATA, bNodeTree, 1, tex->nodetree);
2228                                 write_nodetree(wd, tex->nodetree);
2229                         }
2230
2231                         write_previews(wd, tex->preview);
2232                 }
2233                 tex = tex->id.next;
2234         }
2235
2236         mywrite_flush(wd);
2237 }
2238
2239 static void write_materials(WriteData *wd, ListBase *idbase)
2240 {
2241         Material *ma;
2242         int a;
2243
2244         ma = idbase->first;
2245         while (ma) {
2246                 if (ma->id.us > 0 || wd->current) {
2247                         /* write LibData */
2248                         writestruct(wd, ID_MA, Material, 1, ma);
2249                         write_iddata(wd, &ma->id);
2250
2251                         if (ma->adt) {
2252                                 write_animdata(wd, ma->adt);
2253                         }
2254
2255                         for (a = 0; a < MAX_MTEX; a++) {
2256                                 if (ma->mtex[a]) {
2257                                         writestruct(wd, DATA, MTex, 1, ma->mtex[a]);
2258                                 }
2259                         }
2260
2261                         if (ma->ramp_col) {
2262                                 writestruct(wd, DATA, ColorBand, 1, ma->ramp_col);
2263                         }
2264                         if (ma->ramp_spec) {
2265                                 writestruct(wd, DATA, ColorBand, 1, ma->ramp_spec);
2266                         }
2267
2268                         /* nodetree is integral part of material, no libdata */
2269                         if (ma->nodetree) {
2270                                 writestruct(wd, DATA, bNodeTree, 1, ma->nodetree);
2271                                 write_nodetree(wd, ma->nodetree);
2272                         }
2273
2274                         write_previews(wd, ma->preview);
2275                 }
2276                 ma = ma->id.next;
2277         }
2278 }
2279
2280 static void write_worlds(WriteData *wd, ListBase *idbase)
2281 {
2282         World *wrld;
2283         int a;
2284
2285         wrld = idbase->first;
2286         while (wrld) {
2287                 if (wrld->id.us > 0 || wd->current) {
2288                         /* write LibData */
2289                         writestruct(wd, ID_WO, World, 1, wrld);
2290                         write_iddata(wd, &wrld->id);
2291
2292                         if (wrld->adt) {
2293                                 write_animdata(wd, wrld->adt);
2294                         }
2295
2296                         for (a = 0; a < MAX_MTEX; a++) {
2297                                 if (wrld->mtex[a]) {
2298                                         writestruct(wd, DATA, MTex, 1, wrld->mtex[a]);
2299                                 }
2300                         }
2301
2302                         /* nodetree is integral part of world, no libdata */
2303                         if (wrld->nodetree) {
2304                                 writestruct(wd, DATA, bNodeTree, 1, wrld->nodetree);
2305                                 write_nodetree(wd, wrld->nodetree);
2306                         }
2307
2308                         write_previews(wd, wrld->preview);
2309                 }
2310                 wrld = wrld->id.next;
2311         }
2312 }
2313
2314 static void write_lamps(WriteData *wd, ListBase *idbase)
2315 {
2316         Lamp *la;
2317         int a;
2318
2319         la = idbase->first;
2320         while (la) {
2321                 if (la->id.us > 0 || wd->current) {
2322                         /* write LibData */
2323                         writestruct(wd, ID_LA, Lamp, 1, la);
2324                         write_iddata(wd, &la->id);
2325
2326                         if (la->adt) {
2327                                 write_animdata(wd, la->adt);
2328                         }
2329
2330                         /* direct data */
2331                         for (a = 0; a < MAX_MTEX; a++) {
2332                                 if (la->mtex[a]) {
2333                                         writestruct(wd, DATA, MTex, 1, la->mtex[a]);
2334                                 }
2335                         }
2336
2337                         if (la->curfalloff) {
2338                                 write_curvemapping(wd, la->curfalloff);
2339                         }
2340
2341                         /* nodetree is integral part of lamps, no libdata */
2342                         if (la->nodetree) {
2343                                 writestruct(wd, DATA, bNodeTree, 1, la->nodetree);
2344                                 write_nodetree(wd, la->nodetree);
2345                         }
2346
2347                         write_previews(wd, la->preview);
2348
2349                 }
2350                 la = la->id.next;
2351         }
2352
2353         mywrite_flush(wd);
2354 }
2355
2356 static void write_sequence_modifiers(WriteData *wd, ListBase *modbase)
2357 {
2358         SequenceModifierData *smd;
2359
2360         for (smd = modbase->first; smd; smd = smd->next) {
2361                 const SequenceModifierTypeInfo *smti = BKE_sequence_modifier_type_info_get(smd->type);
2362
2363                 if (smti) {
2364                         writestruct_id(wd, DATA, smti->struct_name, 1, smd);
2365
2366                         if (smd->type == seqModifierType_Curves) {
2367                                 CurvesModifierData *cmd = (CurvesModifierData *)smd;
2368
2369                                 write_curvemapping(wd, &cmd->curve_mapping);
2370                         }
2371                         else if (smd->type == seqModifierType_HueCorrect) {
2372                                 HueCorrectModifierData *hcmd = (HueCorrectModifierData *)smd;
2373
2374                                 write_curvemapping(wd, &hcmd->curve_mapping);
2375                         }
2376                 }
2377                 else {
2378                         writestruct(wd, DATA, SequenceModifierData, 1, smd);
2379                 }
2380         }
2381 }
2382
2383 static void write_view_settings(WriteData *wd, ColorManagedViewSettings *view_settings)
2384 {
2385         if (view_settings->curve_mapping) {
2386                 write_curvemapping(wd, view_settings->curve_mapping);
2387         }
2388 }
2389
2390 static void write_paint(WriteData *wd, Paint *p)
2391 {
2392         if (p->cavity_curve) {
2393                 write_curvemapping(wd, p->cavity_curve);
2394         }
2395 }
2396
2397 static void write_scenes(WriteData *wd, ListBase *scebase)
2398 {
2399         Scene *sce;
2400         Base *base;
2401         Editing *ed;
2402         Sequence *seq;
2403         MetaStack *ms;
2404         Strip *strip;
2405         TimeMarker *marker;
2406         TransformOrientation *ts;
2407         SceneRenderLayer *srl;
2408         SceneRenderView *srv;
2409         ToolSettings *tos;
2410         FreestyleModuleConfig *fmc;
2411         FreestyleLineSet *fls;
2412
2413         sce = scebase->first;
2414         while (sce) {
2415                 /* write LibData */
2416                 writestruct(wd, ID_SCE, Scene, 1, sce);
2417                 write_iddata(wd, &sce->id);
2418
2419                 if (sce->adt) {
2420                         write_animdata(wd, sce->adt);
2421                 }
2422                 write_keyingsets(wd, &sce->keyingsets);
2423
2424                 /* direct data */
2425                 base = sce->base.first;
2426                 while (base) {
2427                         writestruct(wd, DATA, Base, 1, base);
2428                         base = base->next;
2429                 }
2430
2431                 tos = sce->toolsettings;
2432                 writestruct(wd, DATA, ToolSettings, 1, tos);
2433                 if (tos->vpaint) {
2434                         writestruct(wd, DATA, VPaint, 1, tos->vpaint);
2435                         write_paint(wd, &tos->vpaint->paint);
2436                 }
2437                 if (tos->wpaint) {
2438                         writestruct(wd, DATA, VPaint, 1, tos->wpaint);
2439                         write_paint(wd, &tos->wpaint->paint);
2440                 }
2441                 if (tos->sculpt) {
2442                         writestruct(wd, DATA, Sculpt, 1, tos->sculpt);
2443                         write_paint(wd, &tos->sculpt->paint);
2444                 }
2445                 if (tos->uvsculpt) {
2446                         writestruct(wd, DATA, UvSculpt, 1, tos->uvsculpt);
2447                         write_paint(wd, &tos->uvsculpt->paint);
2448                 }
2449                 /* write grease-pencil drawing brushes to file */
2450                 writelist(wd, DATA, bGPDbrush, &tos->gp_brushes);
2451                 for (bGPDbrush *brush = tos->gp_brushes.first; brush; brush = brush->next) {
2452                         if (brush->cur_sensitivity) {
2453                                 write_curvemapping(wd, brush->cur_sensitivity);
2454                         }
2455                         if (brush->cur_strength) {
2456                                 write_curvemapping(wd, brush->cur_strength);
2457                         }
2458                         if (brush->cur_jitter) {
2459                                 write_curvemapping(wd, brush->cur_jitter);
2460                         }
2461                 }
2462                 
2463
2464                 write_paint(wd, &tos->imapaint.paint);
2465
2466                 ed = sce->ed;
2467                 if (ed) {
2468                         writestruct(wd, DATA, Editing, 1, ed);
2469
2470                         /* reset write flags too */
2471
2472                         SEQ_BEGIN(ed, seq)
2473                         {
2474                                 if (seq->strip) {
2475                                         seq->strip->done = false;
2476                                 }
2477                                 writestruct(wd, DATA, Sequence, 1, seq);
2478                         }
2479                         SEQ_END
2480
2481                         SEQ_BEGIN(ed, seq)
2482                         {
2483                                 if (seq->strip && seq->strip->done == 0) {
2484                                         /* write strip with 'done' at 0 because readfile */
2485
2486                                         if (seq->effectdata) {
2487                                                 switch (seq->type) {
2488                                                         case SEQ_TYPE_COLOR:
2489                                                                 writestruct(wd, DATA, SolidColorVars, 1, seq->effectdata);
2490                                                                 break;
2491                                                         case SEQ_TYPE_SPEED:
2492                                                                 writestruct(wd, DATA, SpeedControlVars, 1, seq->effectdata);
2493                                                                 break;
2494                                                         case SEQ_TYPE_WIPE:
2495                                                                 writestruct(wd, DATA, WipeVars, 1, seq->effectdata);
2496                                                                 break;
2497                                                         case SEQ_TYPE_GLOW:
2498                                                                 writestruct(wd, DATA, GlowVars, 1, seq->effectdata);
2499                                                                 break;
2500                                                         case SEQ_TYPE_TRANSFORM:
2501                                                                 writestruct(wd, DATA, TransformVars, 1, seq->effectdata);
2502                                                                 break;
2503                                                         case SEQ_TYPE_GAUSSIAN_BLUR:
2504                                                                 writestruct(wd, DATA, GaussianBlurVars, 1, seq->effectdata);
2505                                                                 break;
2506                                                         case SEQ_TYPE_TEXT:
2507                                                                 writestruct(wd, DATA, TextVars, 1, seq->effectdata);
2508                                                                 break;
2509                                                 }
2510                                         }
2511
2512                                         writestruct(wd, DATA, Stereo3dFormat, 1, seq->stereo3d_format);
2513
2514                                         strip = seq->strip;
2515                                         writestruct(wd, DATA, Strip, 1, strip);
2516                                         if (seq->flag & SEQ_USE_CROP && strip->crop) {
2517                                                 writestruct(wd, DATA, StripCrop, 1, strip->crop);
2518                                         }
2519                                         if (seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
2520                                                 writestruct(wd, DATA, StripTransform, 1, strip->transform);
2521                                         }
2522                                         if (seq->flag & SEQ_USE_PROXY && strip->proxy) {
2523                                                 writestruct(wd, DATA, StripProxy, 1, strip->proxy);
2524                                         }
2525                                         if (seq->type == SEQ_TYPE_IMAGE) {
2526                                                 writestruct(wd, DATA, StripElem,
2527                                                             MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem),
2528                                                             strip->stripdata);
2529                                         }
2530                                         else if (ELEM(seq->type, SEQ_TYPE_MOVIE, SEQ_TYPE_SOUND_RAM, SEQ_TYPE_SOUND_HD)) {
2531                                                 writestruct(wd, DATA, StripElem, 1, strip->stripdata);
2532                                         }
2533
2534                                         strip->done = true;
2535                                 }
2536
2537                                 if (seq->prop) {
2538                                         IDP_WriteProperty(seq->prop, wd);
2539                                 }
2540
2541                                 write_sequence_modifiers(wd, &seq->modifiers);
2542                         }
2543                         SEQ_END
2544
2545                         /* new; meta stack too, even when its nasty restore code */
2546                         for (ms = ed->metastack.first; ms; ms = ms->next) {
2547                                 writestruct(wd, DATA, MetaStack, 1, ms);
2548                         }
2549                 }
2550
2551                 if (sce->r.avicodecdata) {
2552                         writestruct(wd, DATA, AviCodecData, 1, sce->r.avicodecdata);
2553                         if (sce->r.avicodecdata->lpFormat) {
2554                                 writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
2555                         }
2556                         if (sce->r.avicodecdata->lpParms) {
2557                                 writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
2558                         }
2559                 }
2560
2561                 if (sce->r.qtcodecdata) {
2562                         writestruct(wd, DATA, QuicktimeCodecData, 1, sce->r.qtcodecdata);
2563                         if (sce->r.qtcodecdata->cdParms) {
2564                                 writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
2565                         }
2566                 }
2567                 if (sce->r.ffcodecdata.properties) {
2568                         IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
2569                 }
2570
2571                 /* writing dynamic list of TimeMarkers to the blend file */
2572                 for (marker = sce->markers.first; marker; marker = marker->next) {
2573                         writestruct(wd, DATA, TimeMarker, 1, marker);
2574                 }
2575
2576                 /* writing dynamic list of TransformOrientations to the blend file */
2577                 for (ts = sce->transform_spaces.first; ts; ts = ts->next) {
2578                         writestruct(wd, DATA, TransformOrientation, 1, ts);
2579                 }
2580
2581                 for (srl = sce->r.layers.first; srl; srl = srl->next) {
2582                         writestruct(wd, DATA, SceneRenderLayer, 1, srl);
2583                         for (fmc = srl->freestyleConfig.modules.first; fmc; fmc = fmc->next) {
2584                                 writestruct(wd, DATA, FreestyleModuleConfig, 1, fmc);
2585                         }
2586                         for (fls = srl->freestyleConfig.linesets.first; fls; fls = fls->next) {
2587                                 writestruct(wd, DATA, FreestyleLineSet, 1, fls);
2588                         }
2589                 }
2590
2591                 /* writing MultiView to the blend file */
2592                 for (srv = sce->r.views.first; srv; srv = srv->next) {
2593                         writestruct(wd, DATA, SceneRenderView, 1, srv);
2594                 }
2595
2596                 if (sce->nodetree) {
2597                         writestruct(wd, DATA, bNodeTree, 1, sce->nodetree);
2598                         write_nodetree(wd, sce->nodetree);
2599                 }
2600
2601                 write_view_settings(wd, &sce->view_settings);
2602
2603                 /* writing RigidBodyWorld data to the blend file */
2604                 if (sce->rigidbody_world) {
2605                         writestruct(wd, DATA, RigidBodyWorld, 1, sce->rigidbody_world);
2606                         writestruct(wd, DATA, EffectorWeights, 1, sce->rigidbody_world->effector_weights);
2607                 }
2608
2609                 write_previews(wd, sce->preview);
2610                 write_curvemapping_curves(wd, &sce->r.mblur_shutter_curve);
2611
2612                 sce = sce->id.next;
2613         }
2614
2615         mywrite_flush(wd);
2616 }
2617
2618 static void write_gpencils(WriteData *wd, ListBase *lb)
2619 {
2620         bGPdata *gpd;
2621         bGPDlayer *gpl;
2622         bGPDframe *gpf;
2623         bGPDstroke *gps;
2624         bGPDpalette *palette;
2625
2626         for (gpd = lb->first; gpd; gpd = gpd->id.next) {
2627                 if (gpd->id.us > 0 || wd->current) {
2628                         /* write gpd data block to file */
2629                         writestruct(wd, ID_GD, bGPdata, 1, gpd);
2630                         write_iddata(wd, &gpd->id);
2631
2632                         if (gpd->adt) {
2633                                 write_animdata(wd, gpd->adt);
2634                         }
2635
2636                         /* write grease-pencil layers to file */
2637                         writelist(wd, DATA, bGPDlayer, &gpd->layers);
2638                         for (gpl = gpd->layers.first; gpl; gpl = gpl->next) {
2639
2640                                 /* write this layer's frames to file */
2641                                 writelist(wd, DATA, bGPDframe, &gpl->frames);
2642                                 for (gpf = gpl->frames.first; gpf; gpf = gpf->next) {
2643
2644                                         /* write strokes */
2645                                         writelist(wd, DATA, bGPDstroke, &gpf->strokes);
2646                                         for (gps = gpf->strokes.first; gps; gps = gps->next) {
2647                                                 writestruct(wd, DATA, bGPDspoint, gps->totpoints, gps->points);
2648                                         }
2649                                 }
2650                         }
2651                         /* write grease-pencil palettes */
2652                         writelist(wd, DATA, bGPDpalette, &gpd->palettes);
2653                         for (palette = gpd->palettes.first; palette; palette = palette->next) {
2654                                 writelist(wd, DATA, bGPDpalettecolor, &palette->colors);
2655                         }
2656                 }
2657         }
2658
2659         mywrite_flush(wd);
2660 }
2661
2662 static void write_windowmanagers(WriteData *wd, ListBase *lb)
2663 {
2664         wmWindowManager *wm;
2665         wmWindow *win;
2666
2667         for (wm = lb->first; wm; wm = wm->id.next) {
2668                 writestruct(wd, ID_WM, wmWindowManager, 1, wm);
2669                 write_iddata(wd, &wm->id);
2670
2671                 for (win = wm->windows.first; win; win = win->next) {
2672                         writestruct(wd, DATA, wmWindow, 1, win);
2673                         writestruct(wd, DATA, Stereo3dFormat, 1, win->stereo3d_format);
2674                 }
2675         }
2676
2677         /* typically flushing wouldn't be needed however this data _always_ changes,
2678          * so flush here for more efficient undo. */
2679         mywrite_flush(wd);
2680 }
2681
2682 static void write_region(WriteData *wd, ARegion *ar, int spacetype)
2683 {
2684         writestruct(wd, DATA, ARegion, 1, ar);
2685
2686         if (ar->regiondata) {
2687                 switch (spacetype) {
2688                         case SPACE_VIEW3D:
2689                                 if (ar->regiontype == RGN_TYPE_WINDOW) {
2690                                         RegionView3D *rv3d = ar->regiondata;
2691                                         writestruct(wd, DATA, RegionView3D, 1, rv3d);
2692
2693                                         if (rv3d->localvd) {
2694                                                 writestruct(wd, DATA, RegionView3D, 1, rv3d->localvd);
2695                                         }
2696                                         if (rv3d->clipbb) {
2697                                                 writestruct(wd, DATA, BoundBox, 1, rv3d->clipbb);
2698                                         }
2699
2700                                 }
2701                                 else
2702                                         printf("regiondata write missing!\n");
2703                                 break;
2704                         default:
2705                                 printf("regiondata write missing!\n");
2706                 }
2707         }
2708 }
2709
2710 static void write_uilist(WriteData *wd, uiList *ui_list)
2711 {
2712         writestruct(wd, DATA, uiList, 1, ui_list);
2713
2714         if (ui_list->properties) {
2715                 IDP_WriteProperty(ui_list->properties, wd);
2716         }
2717 }
2718
2719 static void write_soops(WriteData *wd, SpaceOops *so)
2720 {
2721         BLI_mempool *ts = so->treestore;
2722
2723         if (ts) {
2724                 SpaceOops so_flat = *so;
2725
2726                 int elems = BLI_mempool_count(ts);
2727                 /* linearize mempool to array */
2728                 TreeStoreElem *data = elems ? BLI_mempool_as_arrayN(ts, "TreeStoreElem") : NULL;
2729
2730                 if (data) {
2731                         /* In this block we use the memory location of the treestore
2732                          * but _not_ its data, the addresses in this case are UUID's,
2733                          * since we can't rely on malloc giving us different values each time.
2734                          */
2735                         TreeStore ts_flat = {0};
2736
2737                         /* we know the treestore is at least as big as a pointer,
2738                          * so offsetting works to give us a UUID. */
2739                         void *data_addr = (void *)POINTER_OFFSET(ts, sizeof(void *));
2740
2741                         ts_flat.usedelem = elems;
2742                         ts_flat.totelem = elems;
2743                         ts_flat.data = data_addr;
2744
2745                         writestruct(wd, DATA, SpaceOops, 1, so);
2746
2747                         writestruct_at_address(wd, DATA, TreeStore, 1, ts, &ts_flat);
2748                         writestruct_at_address(wd, DATA, TreeStoreElem, elems, data_addr, data);
2749
2750                         MEM_freeN(data);
2751                 }
2752                 else {
2753                         so_flat.treestore = NULL;
2754                         writestruct_at_address(wd, DATA, SpaceOops, 1, so, &so_flat);
2755                 }
2756         }
2757         else {
2758                 writestruct(wd, DATA, SpaceOops, 1, so);
2759         }
2760 }
2761
2762 static void write_screens(WriteData *wd, ListBase *scrbase)
2763 {
2764         bScreen *sc;
2765         ScrArea *sa;
2766         ScrVert *sv;
2767         ScrEdge *se;
2768
2769         sc = scrbase->first;
2770         while (sc) {
2771
2772                 /* write LibData */
2773                 /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
2774                 writestruct(wd, ID_SCRN, bScreen, 1, sc);
2775                 write_iddata(wd, &sc->id);
2776
2777                 /* direct data */
2778                 for (sv = sc->vertbase.first; sv; sv = sv->next) {
2779                         writestruct(wd, DATA, ScrVert, 1, sv);
2780                 }
2781
2782                 for (se = sc->edgebase.first; se; se = se->next) {
2783                         writestruct(wd, DATA, ScrEdge, 1, se);
2784                 }
2785
2786                 for (sa = sc->areabase.first; sa; sa = sa->next) {
2787                         SpaceLink *sl;
2788                         Panel *pa;
2789                         uiList *ui_list;
2790                         uiPreview *ui_preview;
2791                         PanelCategoryStack *pc_act;
2792                         ARegion *ar;
2793
2794                         writestruct(wd, DATA, ScrArea, 1, sa);
2795
2796                         for (ar = sa->regionbase.first; ar; ar = ar->next) {
2797                                 write_region(wd, ar, sa->spacetype);
2798
2799                                 for (pa = ar->panels.first; pa; pa = pa->next) {
2800                                         writestruct(wd, DATA, Panel, 1, pa);
2801                                 }
2802
2803                                 for (pc_act = ar->panels_category_active.first; pc_act; pc_act = pc_act->next) {
2804                                         writestruct(wd, DATA, PanelCategoryStack, 1, pc_act);
2805                                 }
2806
2807                                 for (ui_list = ar->ui_lists.first; ui_list; ui_list = ui_list->next) {
2808                                         write_uilist(wd, ui_list);
2809                                 }
2810
2811                                 for (ui_preview = ar->ui_previews.first; ui_preview; ui_preview = ui_preview->next) {
2812                                         writestruct(wd, DATA, uiPreview, 1, ui_preview);
2813                                 }
2814                         }
2815
2816                         sl = sa->spacedata.first;
2817                         while (sl) {
2818                                 for (ar = sl->regionbase.first; ar; ar = ar->next) {
2819                                         write_region(wd, ar, sl->spacetype);
2820                                 }
2821
2822                                 if (sl->spacetype == SPACE_VIEW3D) {
2823                                         View3D *v3d = (View3D *)sl;
2824                                         BGpic *bgpic;
2825                                         writestruct(wd, DATA, View3D, 1, v3d);
2826                                         for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
2827                                                 writestruct(wd, DATA, BGpic, 1, bgpic);
2828                                         }
2829                                         if (v3d->localvd) {
2830                                                 writestruct(wd, DATA, View3D, 1, v3d->localvd);
2831                                         }
2832
2833                                         if (v3d->fx_settings.ssao) {
2834                                                 writestruct(wd, DATA, GPUSSAOSettings, 1, v3d->fx_settings.ssao);
2835                                         }
2836                                         if (v3d->fx_settings.dof) {
2837                                                 writestruct(wd, DATA, GPUDOFSettings, 1, v3d->fx_settings.dof);
2838                                         }
2839                                 }
2840                                 else if (sl->spacetype == SPACE_IPO) {
2841                                         SpaceIpo *sipo = (SpaceIpo *)sl;
2842                                         ListBase tmpGhosts = sipo->ghostCurves;
2843
2844                                         /* temporarily disable ghost curves when saving */
2845                                         sipo->ghostCurves.first = sipo->ghostCurves.last = NULL;
2846
2847                                         writestruct(wd, DATA, SpaceIpo, 1, sl);
2848                                         if (sipo->ads) {
2849                                                 writestruct(wd, DATA, bDopeSheet, 1, sipo->ads);
2850                                         }
2851
2852                                         /* reenable ghost curves */
2853                                         sipo->ghostCurves = tmpGhosts;
2854                                 }
2855                                 else if (sl->spacetype == SPACE_BUTS) {
2856                                         writestruct(wd, DATA, SpaceButs, 1, sl);
2857                                 }
2858                                 else if (sl->spacetype == SPACE_FILE) {
2859                                         SpaceFile *sfile = (SpaceFile *)sl;
2860
2861                                         writestruct(wd, DATA, SpaceFile, 1, sl);
2862                                         if (sfile->params) {
2863                                                 writestruct(wd, DATA, FileSelectParams, 1, sfile->params);
2864                                         }
2865                                 }
2866                                 else if (sl->spacetype == SPACE_SEQ) {
2867                                         writestruct(wd, DATA, SpaceSeq, 1, sl);
2868                                 }
2869                                 else if (sl->spacetype == SPACE_OUTLINER) {
2870                                         SpaceOops *so = (SpaceOops *)sl;
2871                                         write_soops(wd, so);
2872                                 }
2873                                 else if (sl->spacetype == SPACE_IMAGE) {
2874                                         writestruct(wd, DATA, SpaceImage, 1, sl);
2875                                 }
2876                                 else if (sl->spacetype == SPACE_TEXT) {
2877                                         writestruct(wd, DATA, SpaceText, 1, sl);
2878                                 }
2879                                 else if (sl->spacetype == SPACE_SCRIPT) {
2880                                         SpaceScript *scr = (SpaceScript *)sl;
2881                                         scr->but_refs = NULL;
2882                                         writestruct(wd, DATA, SpaceScript, 1, sl);
2883                                 }
2884                                 else if (sl->spacetype == SPACE_ACTION) {
2885                                         writestruct(wd, DATA, SpaceAction, 1, sl);
2886                                 }
2887                                 else if (sl->spacetype == SPACE_NLA) {
2888                                         SpaceNla *snla = (SpaceNla *)sl;
2889
2890                                         writestruct(wd, DATA, SpaceNla, 1, snla);
2891                                         if (snla->ads) {
2892                                                 writestruct(wd, DATA, bDopeSheet, 1, snla->ads);
2893                                         }
2894                                 }
2895                                 else if (sl->spacetype == SPACE_TIME) {
2896                                         writestruct(wd, DATA, SpaceTime, 1, sl);
2897                                 }
2898                                 else if (sl->spacetype == SPACE_NODE) {
2899                                         SpaceNode *snode = (SpaceNode *)sl;
2900                                         bNodeTreePath *path;
2901                                         writestruct(wd, DATA, SpaceNode, 1, snode);
2902
2903                                         for (path = snode->treepath.first; path; path = path->next) {
2904                                                 writestruct(wd, DATA, bNodeTreePath, 1, path);
2905                                         }
2906                                 }
2907                                 else if (sl->spacetype == SPACE_LOGIC) {
2908                                         writestruct(wd, DATA, SpaceLogic, 1, sl);
2909                                 }
2910                                 else if (sl->spacetype == SPACE_CONSOLE) {
2911                                         SpaceConsole *con = (SpaceConsole *)sl;
2912                                         ConsoleLine *cl;
2913
2914                                         for (cl = con->history.first; cl; cl = cl->next) {
2915                                                 /* 'len_alloc' is invalid on write, set from 'len' on read */
2916                                                 writestruct(wd, DATA, ConsoleLine, 1, cl);
2917                                                 writedata(wd, DATA, cl->len + 1, cl->line);
2918                                         }
2919                                         writestruct(wd, DATA, SpaceConsole, 1, sl);
2920
2921                                 }
2922                                 else if (sl->spacetype == SPACE_USERPREF) {
2923                                         writestruct(wd, DATA, SpaceUserPref, 1, sl);
2924                                 }
2925                                 else if (sl->spacetype == SPACE_CLIP) {
2926                                         writestruct(wd, DATA, SpaceClip, 1, sl);
2927                                 }
2928                                 else if (sl->spacetype == SPACE_INFO) {
2929                                         writestruct(wd, DATA, SpaceInfo, 1, sl);
2930                                 }
2931
2932                                 sl = sl->next;
2933                         }
2934                 }
2935
2936                 sc = sc->id.next;
2937         }
2938
2939         mywrite_flush(wd);
2940 }
2941
2942 static void write_bone(WriteData *wd, Bone *bone)
2943 {
2944         /* PATCH for upward compatibility after 2.37+ armature recode */
2945         bone->size[0] = bone->size[1] = bone->size[2] = 1.0f;
2946
2947         /* Write this bone */
2948         writestruct(wd, DATA, Bone, 1, bone);
2949
2950         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
2951          * of library blocks that implement this.*/
2952         if (bone->prop) {
2953                 IDP_WriteProperty(bone->prop, wd);
2954         }
2955
2956         /* Write Children */
2957         for (Bone *cbone = bone->childbase.first; cbone; cbone = cbone->next) {
2958                 write_bone(wd, cbone);
2959         }
2960 }
2961
2962 static void write_armatures(WriteData *wd, ListBase *idbase)
2963 {
2964         bArmature   *arm;
2965         Bone        *bone;
2966
2967         arm = idbase->first;
2968         while (arm) {
2969                 if (arm->id.us > 0 || wd->current) {
2970                         writestruct(wd, ID_AR, bArmature, 1, arm);
2971                         write_iddata(wd, &arm->id);
2972
2973                         if (arm->adt) {
2974                                 write_animdata(wd, arm->adt);
2975                         }
2976
2977                         /* Direct data */
2978                         bone = arm->bonebase.first;
2979                         while (bone) {
2980                                 write_bone(wd, bone);
2981                                 bone = bone->next;
2982                         }
2983                 }
2984                 arm = arm->id.next;
2985         }
2986
2987         mywrite_flush(wd);
2988 }
2989
2990 static void write_texts(WriteData *wd, ListBase *idbase)
2991 {
2992         Text *text;
2993         TextLine *tmp;
2994
2995         text = idbase->first;
2996         while (text) {
2997                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) {
2998                         text->flags &= ~TXT_ISEXT;
2999                 }
3000
3001                 /* write LibData */
3002                 writestruct(wd, ID_TXT, Text, 1, text);
3003                 write_iddata(wd, &text->id);
3004
3005                 if (text->name) {
3006                         writedata(wd, DATA, strlen(text->name) + 1, text->name);
3007                 }
3008
3009                 if (!(text->flags & TXT_ISEXT)) {
3010                         /* now write the text data, in two steps for optimization in the readfunction */
3011                         tmp = text->lines.first;
3012                         while (tmp) {
3013                                 writestruct(wd, DATA, TextLine, 1, tmp);
3014                                 tmp = tmp->next;
3015                         }
3016
3017                         tmp = text->lines.first;
3018                         while (tmp) {
3019                                 writedata(wd, DATA, tmp->len + 1, tmp->line);
3020                                 tmp = tmp->next;
3021                         }
3022                 }
3023
3024
3025               &