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