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