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