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