code cleanup: split out defines in BKE_utildefines.h into BLO_blend_defs.h and ui...
[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_meta_types.h"
112 #include "DNA_mesh_types.h"
113 #include "DNA_meshdata_types.h"
114 #include "DNA_material_types.h"
115 #include "DNA_node_types.h"
116 #include "DNA_object_types.h"
117 #include "DNA_object_force.h"
118 #include "DNA_packedFile_types.h"
119 #include "DNA_particle_types.h"
120 #include "DNA_property_types.h"
121 #include "DNA_scene_types.h"
122 #include "DNA_sdna_types.h"
123 #include "DNA_sequence_types.h"
124 #include "DNA_sensor_types.h"
125 #include "DNA_smoke_types.h"
126 #include "DNA_space_types.h"
127 #include "DNA_screen_types.h"
128 #include "DNA_speaker_types.h"
129 #include "DNA_sound_types.h"
130 #include "DNA_text_types.h"
131 #include "DNA_view3d_types.h"
132 #include "DNA_vfont_types.h"
133 #include "DNA_world_types.h"
134 #include "DNA_windowmanager_types.h"
135 #include "DNA_movieclip_types.h"
136 #include "DNA_mask_types.h"
137
138 #include "MEM_guardedalloc.h" // MEM_freeN
139 #include "BLI_bitmap.h"
140 #include "BLI_blenlib.h"
141 #include "BLI_linklist.h"
142 #include "BLI_bpath.h"
143 #include "BLI_math.h"
144 #include "BLI_utildefines.h"
145
146 #include "BKE_action.h"
147 #include "BKE_blender.h"
148 #include "BKE_curve.h"
149 #include "BKE_constraint.h"
150 #include "BKE_global.h" // for G
151 #include "BKE_library.h" // for  set_listbasepointers
152 #include "BKE_main.h"
153 #include "BKE_node.h"
154 #include "BKE_report.h"
155 #include "BKE_sequencer.h"
156 #include "BKE_subsurf.h"
157 #include "BKE_utildefines.h"
158 #include "BKE_modifier.h"
159 #include "BKE_fcurve.h"
160 #include "BKE_pointcache.h"
161 #include "BKE_mesh.h"
162
163 #include "BLO_writefile.h"
164 #include "BLO_readfile.h"
165 #include "BLO_undofile.h"
166 #include "BLO_blend_defs.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         ToolSettings *tos;
2135         
2136         sce= scebase->first;
2137         while (sce) {
2138                 /* write LibData */
2139                 writestruct(wd, ID_SCE, "Scene", 1, sce);
2140                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
2141                 
2142                 if (sce->adt) write_animdata(wd, sce->adt);
2143                 write_keyingsets(wd, &sce->keyingsets);
2144                 
2145                 /* direct data */
2146                 base= sce->base.first;
2147                 while (base) {
2148                         writestruct(wd, DATA, "Base", 1, base);
2149                         base= base->next;
2150                 }
2151                 
2152                 tos = sce->toolsettings;
2153                 writestruct(wd, DATA, "ToolSettings", 1, tos);
2154                 if (tos->vpaint) {
2155                         writestruct(wd, DATA, "VPaint", 1, tos->vpaint);
2156                 }
2157                 if (tos->wpaint) {
2158                         writestruct(wd, DATA, "VPaint", 1, tos->wpaint);
2159                 }
2160                 if (tos->sculpt) {
2161                         writestruct(wd, DATA, "Sculpt", 1, tos->sculpt);
2162                 }
2163                 if (tos->uvsculpt) {
2164                         writestruct(wd, DATA, "UvSculpt", 1, tos->uvsculpt);
2165                 }
2166
2167                 // write_paint(wd, &tos->imapaint.paint);
2168
2169                 ed= sce->ed;
2170                 if (ed) {
2171                         writestruct(wd, DATA, "Editing", 1, ed);
2172                         
2173                         /* reset write flags too */
2174                         
2175                         SEQ_BEGIN (ed, seq)
2176                         {
2177                                 if (seq->strip) seq->strip->done = FALSE;
2178                                 writestruct(wd, DATA, "Sequence", 1, seq);
2179                         }
2180                         SEQ_END
2181                         
2182                         SEQ_BEGIN (ed, seq)
2183                         {
2184                                 if (seq->strip && seq->strip->done==0) {
2185                                         /* write strip with 'done' at 0 because readfile */
2186                                         
2187                                         if (seq->effectdata) {
2188                                                 switch (seq->type) {
2189                                                 case SEQ_TYPE_COLOR:
2190                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
2191                                                         break;
2192                                                 case SEQ_TYPE_SPEED:
2193                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
2194                                                         break;
2195                                                 case SEQ_TYPE_WIPE:
2196                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
2197                                                         break;
2198                                                 case SEQ_TYPE_GLOW:
2199                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
2200                                                         break;
2201                                                 case SEQ_TYPE_TRANSFORM:
2202                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
2203                                                         break;
2204                                                 }
2205                                         }
2206                                         
2207                                         strip= seq->strip;
2208                                         writestruct(wd, DATA, "Strip", 1, strip);
2209                                         if (seq->flag & SEQ_USE_CROP && strip->crop) {
2210                                                 writestruct(wd, DATA, "StripCrop", 1, strip->crop);
2211                                         }
2212                                         if (seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
2213                                                 writestruct(wd, DATA, "StripTransform", 1, strip->transform);
2214                                         }
2215                                         if (seq->flag & SEQ_USE_PROXY && strip->proxy) {
2216                                                 writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
2217                                         }
2218                                         if (seq->flag & SEQ_USE_COLOR_BALANCE && strip->color_balance) {
2219                                                 writestruct(wd, DATA, "StripColorBalance", 1, strip->color_balance);
2220                                         }
2221                                         if (seq->type==SEQ_TYPE_IMAGE)
2222                                                 writestruct(wd, DATA, "StripElem", MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem), strip->stripdata);
2223                                         else if (seq->type==SEQ_TYPE_MOVIE || seq->type==SEQ_TYPE_SOUND_RAM || seq->type == SEQ_TYPE_SOUND_HD)
2224                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
2225                                         
2226                                         strip->done = TRUE;
2227                                 }
2228
2229                                 write_sequence_modifiers(wd, &seq->modifiers);
2230                         }
2231                         SEQ_END
2232                                 
2233                         /* new; meta stack too, even when its nasty restore code */
2234                         for (ms= ed->metastack.first; ms; ms= ms->next) {
2235                                 writestruct(wd, DATA, "MetaStack", 1, ms);
2236                         }
2237                 }
2238                 
2239                 if (sce->r.avicodecdata) {
2240                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
2241                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
2242                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
2243                 }
2244
2245                 if (sce->r.qtcodecdata) {
2246                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
2247                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
2248                 }
2249                 if (sce->r.ffcodecdata.properties) {
2250                         IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
2251                 }
2252
2253                 /* writing dynamic list of TimeMarkers to the blend file */
2254                 for (marker= sce->markers.first; marker; marker= marker->next)
2255                         writestruct(wd, DATA, "TimeMarker", 1, marker);
2256                 
2257                 /* writing dynamic list of TransformOrientations to the blend file */
2258                 for (ts = sce->transform_spaces.first; ts; ts = ts->next)
2259                         writestruct(wd, DATA, "TransformOrientation", 1, ts);
2260                 
2261                 for (srl= sce->r.layers.first; srl; srl= srl->next)
2262                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
2263                 
2264                 if (sce->nodetree) {
2265                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
2266                         write_nodetree(wd, sce->nodetree);
2267                 }
2268                 
2269                 sce= sce->id.next;
2270         }
2271         /* flush helps the compression for undo-save */
2272         mywrite(wd, MYWRITE_FLUSH, 0);
2273 }
2274
2275 static void write_gpencils(WriteData *wd, ListBase *lb)
2276 {
2277         bGPdata *gpd;
2278         bGPDlayer *gpl;
2279         bGPDframe *gpf;
2280         bGPDstroke *gps;
2281         
2282         for (gpd= lb->first; gpd; gpd= gpd->id.next) {
2283                 if (gpd->id.us>0 || wd->current) {
2284                         /* write gpd data block to file */
2285                         writestruct(wd, ID_GD, "bGPdata", 1, gpd);
2286                         
2287                         /* write grease-pencil layers to file */
2288                         for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
2289                                 writestruct(wd, DATA, "bGPDlayer", 1, gpl);
2290                                 
2291                                 /* write this layer's frames to file */
2292                                 for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
2293                                         writestruct(wd, DATA, "bGPDframe", 1, gpf);
2294                                         
2295                                         /* write strokes */
2296                                         for (gps= gpf->strokes.first; gps; gps= gps->next) {
2297                                                 writestruct(wd, DATA, "bGPDstroke", 1, gps);
2298                                                 writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);                               
2299                                         }
2300                                 }
2301                         }
2302                 }
2303         }
2304 }
2305
2306 static void write_windowmanagers(WriteData *wd, ListBase *lb)
2307 {
2308         wmWindowManager *wm;
2309         wmWindow *win;
2310         
2311         for (wm= lb->first; wm; wm= wm->id.next) {
2312                 writestruct(wd, ID_WM, "wmWindowManager", 1, wm);
2313                 
2314                 for (win= wm->windows.first; win; win= win->next)
2315                         writestruct(wd, DATA, "wmWindow", 1, win);
2316         }
2317 }
2318
2319 static void write_region(WriteData *wd, ARegion *ar, int spacetype)
2320 {       
2321         writestruct(wd, DATA, "ARegion", 1, ar);
2322         
2323         if (ar->regiondata) {
2324                 switch (spacetype) {
2325                         case SPACE_VIEW3D:
2326                                 if (ar->regiontype==RGN_TYPE_WINDOW) {
2327                                         RegionView3D *rv3d= ar->regiondata;
2328                                         writestruct(wd, DATA, "RegionView3D", 1, rv3d);
2329                                         
2330                                         if (rv3d->localvd)
2331                                                 writestruct(wd, DATA, "RegionView3D", 1, rv3d->localvd);
2332                                         if (rv3d->clipbb)
2333                                                 writestruct(wd, DATA, "BoundBox", 1, rv3d->clipbb);
2334
2335                                 }
2336                                 else
2337                                         printf("regiondata write missing!\n");
2338                                 break;
2339                         default:
2340                                 printf("regiondata write missing!\n");
2341                 }
2342         }
2343 }
2344
2345 static void write_screens(WriteData *wd, ListBase *scrbase)
2346 {
2347         bScreen *sc;
2348         ScrArea *sa;
2349         ScrVert *sv;
2350         ScrEdge *se;
2351
2352         sc= scrbase->first;
2353         while (sc) {
2354                 
2355                 /* write LibData */
2356                 /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
2357                 writestruct(wd, ID_SCRN, "Screen", 1, sc);
2358                 if (sc->id.properties) 
2359                         IDP_WriteProperty(sc->id.properties, wd);
2360                 
2361                 /* direct data */
2362                 for (sv= sc->vertbase.first; sv; sv= sv->next)
2363                         writestruct(wd, DATA, "ScrVert", 1, sv);
2364                 
2365                 for (se= sc->edgebase.first; se; se= se->next)
2366                         writestruct(wd, DATA, "ScrEdge", 1, se);
2367                 
2368                 for (sa= sc->areabase.first; sa; sa= sa->next) {
2369                         SpaceLink *sl;
2370                         Panel *pa;
2371                         ARegion *ar;
2372                         
2373                         writestruct(wd, DATA, "ScrArea", 1, sa);
2374                         
2375                         for (ar= sa->regionbase.first; ar; ar= ar->next) {
2376                                 write_region(wd, ar, sa->spacetype);
2377                                 
2378                                 for (pa= ar->panels.first; pa; pa= pa->next)
2379                                         writestruct(wd, DATA, "Panel", 1, pa);
2380                         }
2381                         
2382                         sl= sa->spacedata.first;
2383                         while (sl) {
2384                                 for (ar= sl->regionbase.first; ar; ar= ar->next)
2385                                         write_region(wd, ar, sl->spacetype);
2386                                 
2387                                 if (sl->spacetype==SPACE_VIEW3D) {
2388                                         View3D *v3d= (View3D *) sl;
2389                                         BGpic *bgpic;
2390                                         writestruct(wd, DATA, "View3D", 1, v3d);
2391                                         for (bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next)
2392                                                 writestruct(wd, DATA, "BGpic", 1, bgpic);
2393                                         if (v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
2394                                 }
2395                                 else if (sl->spacetype==SPACE_IPO) {
2396                                         SpaceIpo *sipo= (SpaceIpo *)sl;
2397                                         ListBase tmpGhosts = sipo->ghostCurves;
2398                                         
2399                                         /* temporarily disable ghost curves when saving */
2400                                         sipo->ghostCurves.first= sipo->ghostCurves.last= NULL;
2401                                         
2402                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
2403                                         if (sipo->ads) writestruct(wd, DATA, "bDopeSheet", 1, sipo->ads);
2404                                         
2405                                         /* reenable ghost curves */
2406                                         sipo->ghostCurves= tmpGhosts;
2407                                 }
2408                                 else if (sl->spacetype==SPACE_BUTS) {
2409                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
2410                                 }
2411                                 else if (sl->spacetype==SPACE_FILE) {
2412                                         SpaceFile *sfile= (SpaceFile *)sl;
2413
2414                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
2415                                         if (sfile->params)
2416                                                 writestruct(wd, DATA, "FileSelectParams", 1, sfile->params);
2417                                 }
2418                                 else if (sl->spacetype==SPACE_SEQ) {
2419                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
2420                                 }
2421                                 else if (sl->spacetype==SPACE_OUTLINER) {
2422                                         SpaceOops *so= (SpaceOops *)sl;
2423                                         
2424                                         writestruct(wd, DATA, "SpaceOops", 1, so);
2425
2426                                         /* outliner */
2427                                         if (so->treestore) {
2428                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
2429                                                 if (so->treestore->data)
2430                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
2431                                         }
2432                                 }
2433                                 else if (sl->spacetype==SPACE_IMAGE) {
2434                                         SpaceImage *sima= (SpaceImage *)sl;
2435                                         
2436                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
2437                                         if (sima->cumap)
2438                                                 write_curvemapping(wd, sima->cumap);
2439                                 }
2440                                 else if (sl->spacetype==SPACE_TEXT) {
2441                                         writestruct(wd, DATA, "SpaceText", 1, sl);
2442                                 }
2443                                 else if (sl->spacetype==SPACE_SCRIPT) {
2444                                         SpaceScript *scr = (SpaceScript*)sl;
2445                                         scr->but_refs = NULL;
2446                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
2447                                 }
2448                                 else if (sl->spacetype==SPACE_ACTION) {
2449                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
2450                                 }
2451                                 else if (sl->spacetype==SPACE_NLA) {
2452                                         SpaceNla *snla= (SpaceNla *)sl;
2453                                         
2454                                         writestruct(wd, DATA, "SpaceNla", 1, snla);
2455                                         if (snla->ads) writestruct(wd, DATA, "bDopeSheet", 1, snla->ads);
2456                                 }
2457                                 else if (sl->spacetype==SPACE_TIME) {
2458                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
2459                                 }
2460                                 else if (sl->spacetype==SPACE_NODE) {
2461                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
2462                                 }
2463                                 else if (sl->spacetype==SPACE_LOGIC) {
2464                                         writestruct(wd, DATA, "SpaceLogic", 1, sl);
2465                                 }
2466                                 else if (sl->spacetype==SPACE_CONSOLE) {
2467                                         SpaceConsole *con = (SpaceConsole*)sl;
2468                                         ConsoleLine *cl;
2469
2470                                         for (cl=con->history.first; cl; cl=cl->next) {
2471                                                 /* 'len_alloc' is invalid on write, set from 'len' on read */
2472                                                 writestruct(wd, DATA, "ConsoleLine", 1, cl);
2473                                                 writedata(wd, DATA, cl->len+1, cl->line);
2474                                         }
2475                                         writestruct(wd, DATA, "SpaceConsole", 1, sl);
2476
2477                                 }
2478                                 else if (sl->spacetype==SPACE_USERPREF) {
2479                                         writestruct(wd, DATA, "SpaceUserPref", 1, sl);
2480                                 }
2481                                 else if (sl->spacetype==SPACE_CLIP) {
2482                                         writestruct(wd, DATA, "SpaceClip", 1, sl);
2483                                 }
2484
2485                                 sl= sl->next;
2486                         }
2487                 }
2488
2489                 sc= sc->id.next;
2490         }
2491 }
2492
2493 static void write_libraries(WriteData *wd, Main *main)
2494 {
2495         ListBase *lbarray[MAX_LIBARRAY];
2496         ID *id;
2497         int a, tot, foundone;
2498
2499         for (; main; main= main->next) {
2500
2501                 a=tot= set_listbasepointers(main, lbarray);
2502
2503                 /* test: is lib being used */
2504                 foundone = FALSE;
2505                 while (tot--) {
2506                         for (id= lbarray[tot]->first; id; id= id->next) {
2507                                 if (id->us>0 && (id->flag & LIB_EXTERN)) {
2508                                         foundone = TRUE;
2509                                         break;
2510                                 }
2511                         }
2512                         if (foundone) break;
2513                 }
2514
2515                 if (foundone) {
2516                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
2517
2518                         while (a--) {
2519                                 for (id= lbarray[a]->first; id; id= id->next) {
2520                                         if (id->us>0 && (id->flag & LIB_EXTERN)) {
2521                                                 writestruct(wd, ID_ID, "ID", 1, id);
2522                                         }
2523                                 }
2524                         }
2525                 }
2526         }
2527 }
2528
2529 static void write_bone(WriteData *wd, Bone *bone)
2530 {
2531         Bone*   cbone;
2532
2533         // PATCH for upward compatibility after 2.37+ armature recode
2534         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
2535                 
2536         // Write this bone
2537         writestruct(wd, DATA, "Bone", 1, bone);
2538
2539         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
2540          * of library blocks that implement this.*/
2541         if (bone->prop)
2542                 IDP_WriteProperty(bone->prop, wd);
2543         
2544         // Write Children
2545         cbone= bone->childbase.first;
2546         while (cbone) {
2547                 write_bone(wd, cbone);
2548                 cbone= cbone->next;
2549         }
2550 }
2551
2552 static void write_armatures(WriteData *wd, ListBase *idbase)
2553 {
2554         bArmature       *arm;
2555         Bone            *bone;
2556
2557         arm=idbase->first;
2558         while (arm) {
2559                 if (arm->id.us>0 || wd->current) {
2560                         writestruct(wd, ID_AR, "bArmature", 1, arm);
2561                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
2562
2563                         if (arm->adt) write_animdata(wd, arm->adt);
2564
2565                         /* Direct data */
2566                         bone= arm->bonebase.first;
2567                         while (bone) {
2568                                 write_bone(wd, bone);
2569                                 bone=bone->next;
2570                         }
2571                 }
2572                 arm=arm->id.next;
2573         }
2574
2575         /* flush helps the compression for undo-save */
2576         mywrite(wd, MYWRITE_FLUSH, 0);
2577 }
2578
2579 static void write_texts(WriteData *wd, ListBase *idbase)
2580 {
2581         Text *text;
2582         TextLine *tmp;
2583         TextMarker *mrk;
2584
2585         text= idbase->first;
2586         while (text) {
2587                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
2588
2589                 /* write LibData */
2590                 writestruct(wd, ID_TXT, "Text", 1, text);
2591                 if (text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
2592                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
2593
2594                 if (!(text->flags & TXT_ISEXT)) {
2595                         /* now write the text data, in two steps for optimization in the readfunction */
2596                         tmp= text->lines.first;
2597                         while (tmp) {
2598                                 writestruct(wd, DATA, "TextLine", 1, tmp);
2599                                 tmp= tmp->next;
2600                         }
2601
2602                         tmp= text->lines.first;
2603                         while (tmp) {
2604                                 writedata(wd, DATA, tmp->len+1, tmp->line);
2605                                 tmp= tmp->next;
2606                         }
2607
2608                         /* write markers */
2609                         mrk= text->markers.first;
2610                         while (mrk) {
2611                                 writestruct(wd, DATA, "TextMarker", 1, mrk);
2612                                 mrk= mrk->next;
2613                         }
2614                 }
2615
2616
2617                 text= text->id.next;
2618         }
2619
2620         /* flush helps the compression for undo-save */
2621         mywrite(wd, MYWRITE_FLUSH, 0);
2622 }
2623
2624 static void write_speakers(WriteData *wd, ListBase *idbase)
2625 {
2626         Speaker *spk;
2627
2628         spk= idbase->first;
2629         while (spk) {
2630                 if (spk->id.us>0 || wd->current) {
2631                         /* write LibData */
2632                         writestruct(wd, ID_SPK, "Speaker", 1, spk);
2633                         if (spk->id.properties) IDP_WriteProperty(spk->id.properties, wd);
2634
2635                         if (spk->adt) write_animdata(wd, spk->adt);
2636                 }
2637                 spk= spk->id.next;
2638         }
2639 }
2640
2641 static void write_sounds(WriteData *wd, ListBase *idbase)
2642 {
2643         bSound *sound;
2644
2645         PackedFile * pf;
2646
2647         sound= idbase->first;
2648         while (sound) {
2649                 if (sound->id.us>0 || wd->current) {
2650                         /* write LibData */
2651                         writestruct(wd, ID_SO, "bSound", 1, sound);
2652                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
2653
2654                         if (sound->packedfile) {
2655                                 pf = sound->packedfile;
2656                                 writestruct(wd, DATA, "PackedFile", 1, pf);
2657                                 writedata(wd, DATA, pf->size, pf->data);
2658                         }
2659                 }
2660                 sound= sound->id.next;
2661         }
2662
2663         /* flush helps the compression for undo-save */
2664         mywrite(wd, MYWRITE_FLUSH, 0);
2665 }
2666
2667 static void write_groups(WriteData *wd, ListBase *idbase)
2668 {
2669         Group *group;
2670         GroupObject *go;
2671
2672         for (group= idbase->first; group; group= group->id.next) {
2673                 if (group->id.us>0 || wd->current) {
2674                         /* write LibData */
2675                         writestruct(wd, ID_GR, "Group", 1, group);
2676                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
2677
2678                         go= group->gobject.first;
2679                         while (go) {
2680                                 writestruct(wd, DATA, "GroupObject", 1, go);
2681                                 go= go->next;
2682                         }
2683                 }
2684         }
2685 }
2686
2687 static void write_nodetrees(WriteData *wd, ListBase *idbase)
2688 {
2689         bNodeTree *ntree;
2690         
2691         for (ntree=idbase->first; ntree; ntree= ntree->id.next) {
2692                 if (ntree->id.us>0 || wd->current) {
2693                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
2694                         write_nodetree(wd, ntree);
2695                         
2696                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
2697                         
2698                         if (ntree->adt) write_animdata(wd, ntree->adt);
2699                 }
2700         }
2701 }
2702
2703 static void write_brushes(WriteData *wd, ListBase *idbase)
2704 {
2705         Brush *brush;
2706         
2707         for (brush=idbase->first; brush; brush= brush->id.next) {
2708                 if (brush->id.us>0 || wd->current) {
2709                         writestruct(wd, ID_BR, "Brush", 1, brush);
2710                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
2711                         
2712                         writestruct(wd, DATA, "MTex", 1, &brush->mtex);
2713                         
2714                         if (brush->curve)
2715                                 write_curvemapping(wd, brush->curve);
2716                 }
2717         }
2718 }
2719
2720 static void write_scripts(WriteData *wd, ListBase *idbase)
2721 {
2722         Script *script;
2723         
2724         for (script=idbase->first; script; script= script->id.next) {
2725                 if (script->id.us>0 || wd->current) {
2726                         writestruct(wd, ID_SCRIPT, "Script", 1, script);
2727                         if (script->id.properties) IDP_WriteProperty(script->id.properties, wd);
2728                 }
2729         }
2730 }
2731
2732 static void write_movieTracks(WriteData *wd, ListBase *tracks)
2733 {
2734         MovieTrackingTrack *track;
2735
2736         track= tracks->first;
2737         while (track) {
2738                 writestruct(wd, DATA, "MovieTrackingTrack", 1, track);
2739
2740                 if (track->markers)
2741                         writestruct(wd, DATA, "MovieTrackingMarker", track->markersnr, track->markers);
2742
2743                 track= track->next;
2744         }
2745 }
2746
2747 static void write_movieReconstruction(WriteData *wd, MovieTrackingReconstruction *reconstruction)
2748 {
2749         if (reconstruction->camnr)
2750                 writestruct(wd, DATA, "MovieReconstructedCamera", reconstruction->camnr, reconstruction->cameras);
2751 }
2752
2753 static void write_movieclips(WriteData *wd, ListBase *idbase)
2754 {
2755         MovieClip *clip;
2756
2757         clip= idbase->first;
2758         while (clip) {
2759                 if (clip->id.us>0 || wd->current) {
2760                         MovieTracking *tracking= &clip->tracking;
2761                         MovieTrackingObject *object;
2762                         writestruct(wd, ID_MC, "MovieClip", 1, clip);
2763
2764                         if (clip->id.properties)
2765                                 IDP_WriteProperty(clip->id.properties, wd);
2766
2767                         if (clip->adt)
2768                                 write_animdata(wd, clip->adt);
2769
2770                         write_movieTracks(wd, &tracking->tracks);
2771                         write_movieReconstruction(wd, &tracking->reconstruction);
2772
2773                         object= tracking->objects.first;
2774                         while (object) {
2775                                 writestruct(wd, DATA, "MovieTrackingObject", 1, object);
2776
2777                                 write_movieTracks(wd, &object->tracks);
2778                                 write_movieReconstruction(wd, &object->reconstruction);
2779
2780                                 object= object->next;
2781                         }
2782                 }
2783
2784                 clip= clip->id.next;
2785         }
2786
2787         /* flush helps the compression for undo-save */
2788         mywrite(wd, MYWRITE_FLUSH, 0);
2789 }
2790
2791 static void write_masks(WriteData *wd, ListBase *idbase)
2792 {
2793         Mask *mask;
2794
2795         mask = idbase->first;
2796         while (mask) {
2797                 if (mask->id.us > 0 || wd->current) {
2798                         MaskLayer *masklay;
2799
2800                         writestruct(wd, ID_MSK, "Mask", 1, mask);
2801
2802                         if (mask->adt)
2803                                 write_animdata(wd, mask->adt);
2804
2805                         for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
2806                                 MaskSpline *spline;
2807                                 MaskLayerShape *masklay_shape;
2808
2809                                 writestruct(wd, DATA, "MaskLayer", 1, masklay);
2810
2811                                 for (spline = masklay->splines.first; spline; spline = spline->next) {
2812                                         int i;
2813
2814                                         void *points_deform = spline->points_deform;
2815                                         spline->points_deform = NULL;
2816
2817                                         writestruct(wd, DATA, "MaskSpline", 1, spline);
2818                                         writestruct(wd, DATA, "MaskSplinePoint", spline->tot_point, spline->points);
2819
2820                                         spline->points_deform = points_deform;
2821
2822                                         for (i = 0; i < spline->tot_point; i++) {
2823                                                 MaskSplinePoint *point = &spline->points[i];
2824
2825                                                 if (point->tot_uw)
2826                                                         writestruct(wd, DATA, "MaskSplinePointUW", point->tot_uw, point->uw);
2827                                         }
2828                                 }
2829
2830                                 for (masklay_shape = masklay->splines_shapes.first; masklay_shape; masklay_shape = masklay_shape->next) {
2831                                         writestruct(wd, DATA, "MaskLayerShape", 1, masklay_shape);
2832                                         writedata(wd, DATA, masklay_shape->tot_vert * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE, masklay_shape->data);
2833                                 }
2834                         }
2835                 }
2836
2837                 mask = mask->id.next;
2838         }
2839
2840         /* flush helps the compression for undo-save */
2841         mywrite(wd, MYWRITE_FLUSH, 0);
2842 }
2843
2844 /* context is usually defined by WM, two cases where no WM is available:
2845  * - for forward compatibility, curscreen has to be saved
2846  * - for undofile, curscene needs to be saved */
2847 static void write_global(WriteData *wd, int fileflags, Main *mainvar)
2848 {
2849         FileGlobal fg;
2850         bScreen *screen;
2851         char subvstr[8];
2852         
2853         /* prevent mem checkers from complaining */
2854         fg.pads= fg.pad= 0;
2855         memset(fg.filename, 0, sizeof(fg.filename));
2856
2857         current_screen_compat(mainvar, &screen);
2858
2859         /* XXX still remap G */
2860         fg.curscreen= screen;
2861         fg.curscene= screen->scene;
2862         fg.displaymode= G.displaymode;
2863         fg.winpos= G.winpos;
2864
2865         /* prevent to save this, is not good convention, and feature with concerns... */
2866         fg.fileflags= (fileflags & ~(G_FILE_NO_UI|G_FILE_RELATIVE_REMAP|G_FILE_MESH_COMPAT));
2867
2868         fg.globalf= G.f;
2869         BLI_strncpy(fg.filename, mainvar->name, sizeof(fg.filename));
2870
2871         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
2872         memcpy(fg.subvstr, subvstr, 4);
2873         
2874         fg.subversion= BLENDER_SUBVERSION;
2875         fg.minversion= BLENDER_MINVERSION;
2876         fg.minsubversion= BLENDER_MINSUBVERSION;
2877 #ifdef WITH_BUILDINFO
2878         {
2879                 extern char build_rev[];
2880                 fg.revision= atoi(build_rev);
2881         }
2882 #else
2883         fg.revision= 0;
2884 #endif
2885         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
2886 }
2887
2888 /* preview image, first 2 values are width and height
2889  * second are an RGBA image (unsigned char)
2890  * note, this uses 'TEST' since new types will segfault on file load for older blender versions.
2891  */
2892 static void write_thumb(WriteData *wd, const int *img)
2893 {
2894         if (img)
2895                 writedata(wd, TEST, (2 + img[0] * img[1]) * sizeof(int), img);
2896 }
2897
2898 /* if MemFile * there's filesave to memory */
2899 static int write_file_handle(Main *mainvar, int handle, MemFile *compare, MemFile *current, 
2900                              int write_user_block, int write_flags, const int *thumb)
2901 {
2902         BHead bhead;
2903         ListBase mainlist;
2904         char buf[16];
2905         WriteData *wd;
2906
2907         blo_split_main(&mainlist, mainvar);
2908
2909         wd= bgnwrite(handle, compare, current);
2910
2911 #ifdef USE_BMESH_SAVE_AS_COMPAT
2912         wd->use_mesh_compat = (write_flags & G_FILE_MESH_COMPAT) != 0;
2913 #endif
2914
2915         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (ENDIAN_ORDER==B_ENDIAN)?'V':'v', BLENDER_VERSION);
2916         mywrite(wd, buf, 12);
2917
2918         write_renderinfo(wd, mainvar);
2919         write_thumb(wd, thumb);
2920         write_global(wd, write_flags, mainvar);
2921
2922         /* no UI save in undo */
2923         if (current==NULL) {
2924                 write_windowmanagers(wd, &mainvar->wm);
2925                 write_screens  (wd, &mainvar->screen);
2926         }
2927         write_movieclips (wd, &mainvar->movieclip);
2928         write_masks    (wd, &mainvar->mask);
2929         write_scenes   (wd, &mainvar->scene);
2930         write_curves   (wd, &mainvar->curve);
2931         write_mballs   (wd, &mainvar->mball);
2932         write_images   (wd, &mainvar->image);
2933         write_cameras  (wd, &mainvar->camera);
2934         write_lamps    (wd, &mainvar->lamp);
2935         write_lattices (wd, &mainvar->latt);
2936         write_vfonts   (wd, &mainvar->vfont);
2937         write_keys     (wd, &mainvar->key);
2938         write_worlds   (wd, &mainvar->world);
2939         write_texts    (wd, &mainvar->text);
2940         write_speakers (wd, &mainvar->speaker);
2941         write_sounds   (wd, &mainvar->sound);
2942         write_groups   (wd, &mainvar->group);
2943         write_armatures(wd, &mainvar->armature);
2944         write_actions  (wd, &mainvar->action);
2945         write_objects  (wd, &mainvar->object);
2946         write_materials(wd, &mainvar->mat);
2947         write_textures (wd, &mainvar->tex);
2948         write_meshs    (wd, &mainvar->mesh);
2949         write_particlesettings(wd, &mainvar->particle);
2950         write_nodetrees(wd, &mainvar->nodetree);
2951         write_brushes  (wd, &mainvar->brush);
2952         write_scripts  (wd, &mainvar->script);
2953         write_gpencils (wd, &mainvar->gpencil);
2954         write_libraries(wd,  mainvar->next);
2955
2956         if (write_user_block) {
2957                 write_userdef(wd);
2958         }
2959                                                         
2960         /* dna as last, because (to be implemented) test for which structs are written */
2961         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
2962
2963         /* end of file */
2964         memset(&bhead, 0, sizeof(BHead));
2965         bhead.code= ENDB;
2966         mywrite(wd, &bhead, sizeof(BHead));
2967
2968         blo_join_main(&mainlist);
2969
2970         return endwrite(wd);
2971 }
2972
2973 /* do reverse file history: .blend1 -> .blend2, .blend -> .blend1 */
2974 /* return: success(0), failure(1) */
2975 static int do_history(const char *name, ReportList *reports)
2976 {
2977         char tempname1[FILE_MAX], tempname2[FILE_MAX];
2978         int hisnr= U.versions;
2979         
2980         if (U.versions==0) return 0;
2981         if (strlen(name)<2) {