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