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