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