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