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