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