- clear some warnings
[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 #include "BLI_utildefines.h"
133
134 #include "BKE_action.h"
135 #include "BKE_blender.h"
136 #include "BKE_curve.h"
137 #include "BKE_constraint.h"
138 #include "BKE_global.h" // for G
139 #include "BKE_library.h" // for  set_listbasepointers
140 #include "BKE_main.h"
141 #include "BKE_node.h"
142 #include "BKE_report.h"
143 #include "BKE_sequencer.h"
144 #include "BKE_utildefines.h"
145 #include "BKE_modifier.h"
146 #include "BKE_fcurve.h"
147 #include "BKE_pointcache.h"
148
149 #include "BLO_writefile.h"
150 #include "BLO_readfile.h"
151 #include "BLO_undofile.h"
152
153 #include "readfile.h"
154
155 #include <errno.h>
156
157 /* ********* my write, buffered writing with minimum size chunks ************ */
158
159 #define MYWRITE_BUFFER_SIZE     100000
160 #define MYWRITE_MAX_CHUNK       32768
161
162 typedef struct {
163         struct SDNA *sdna;
164
165         int file;
166         unsigned char *buf;
167         MemFile *compare, *current;
168         
169         int tot, count, error, memsize;
170 } WriteData;
171
172 static WriteData *writedata_new(int file)
173 {
174         WriteData *wd= MEM_callocN(sizeof(*wd), "writedata");
175
176                 /* XXX, see note about this in readfile.c, remove
177                  * once we have an xp lock - zr
178                  */
179
180         if (wd == NULL) return NULL;
181
182         wd->sdna= DNA_sdna_from_data(DNAstr, DNAlen, 0);
183
184         wd->file= file;
185
186         wd->buf= MEM_mallocN(MYWRITE_BUFFER_SIZE, "wd->buf");
187
188         return wd;
189 }
190
191 static void writedata_do_write(WriteData *wd, void *mem, int memlen)
192 {
193         if ((wd == NULL) || wd->error || (mem == NULL) || memlen < 1) return;
194         if (wd->error) return;
195
196         /* memory based save */
197         if(wd->current) {
198                 add_memfilechunk(NULL, wd->current, mem, memlen);
199         }
200         else {
201                 if (write(wd->file, mem, memlen) != memlen)
202                         wd->error= 1;
203                 
204         }
205 }
206
207 static void writedata_free(WriteData *wd)
208 {
209         DNA_sdna_free(wd->sdna);
210
211         MEM_freeN(wd->buf);
212         MEM_freeN(wd);
213 }
214
215 /***/
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==NULL) 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
770 /* update this also to readfile.c */
771 static const char *ptcache_data_struct[] = {
772         "", // BPHYS_DATA_INDEX
773         "", // BPHYS_DATA_LOCATION
774         "", // BPHYS_DATA_VELOCITY
775         "", // BPHYS_DATA_ROTATION
776         "", // BPHYS_DATA_AVELOCITY / BPHYS_DATA_XCONST */
777         "", // BPHYS_DATA_SIZE:
778         "", // BPHYS_DATA_TIMES:        
779         "BoidData" // case BPHYS_DATA_BOIDS:
780 };
781 static const char *ptcache_extra_struct[] = {
782         "",
783         "ParticleSpring"
784 };
785 static void write_pointcaches(WriteData *wd, ListBase *ptcaches)
786 {
787         PointCache *cache = ptcaches->first;
788         int i;
789
790         for(; cache; cache=cache->next) {
791                 writestruct(wd, DATA, "PointCache", 1, cache);
792
793                 if((cache->flag & PTCACHE_DISK_CACHE)==0) {
794                         PTCacheMem *pm = cache->mem_cache.first;
795
796                         for(; pm; pm=pm->next) {
797                                 PTCacheExtra *extra = pm->extradata.first;
798
799                                 writestruct(wd, DATA, "PTCacheMem", 1, pm);
800                                 
801                                 for(i=0; i<BPHYS_TOT_DATA; i++) {
802                                         if(pm->data[i] && pm->data_types & (1<<i)) {
803                                                 if(strcmp(ptcache_data_struct[i], "")==0)
804                                                         writedata(wd, DATA, MEM_allocN_len(pm->data[i]), pm->data[i]);
805                                                 else
806                                                         writestruct(wd, DATA, ptcache_data_struct[i], pm->totpoint, pm->data[i]);
807                                         }
808                                 }
809
810                                 for(; extra; extra=extra->next) {
811                                         if(strcmp(ptcache_extra_struct[extra->type], "")==0)
812                                                 continue;
813                                         writestruct(wd, DATA, "PTCacheExtra", 1, extra);
814                                         writestruct(wd, DATA, ptcache_extra_struct[extra->type], extra->totdata, extra->data);
815                                 }
816                         }
817                 }
818         }
819 }
820 static void write_particlesettings(WriteData *wd, ListBase *idbase)
821 {
822         ParticleSettings *part;
823         ParticleDupliWeight *dw;
824         int a;
825
826         part= idbase->first;
827         while(part) {
828                 if(part->id.us>0 || wd->current) {
829                         /* write LibData */
830                         writestruct(wd, ID_PA, "ParticleSettings", 1, part);
831                         if (part->id.properties) IDP_WriteProperty(part->id.properties, wd);
832                         if (part->adt) write_animdata(wd, part->adt);
833                         writestruct(wd, DATA, "PartDeflect", 1, part->pd);
834                         writestruct(wd, DATA, "PartDeflect", 1, part->pd2);
835                         writestruct(wd, DATA, "EffectorWeights", 1, part->effector_weights);
836
837                         dw = part->dupliweights.first;
838                         for(; dw; dw=dw->next)
839                                 writestruct(wd, DATA, "ParticleDupliWeight", 1, dw);
840
841                         if(part->boids && part->phystype == PART_PHYS_BOIDS) {
842                                 BoidState *state = part->boids->states.first;
843
844                                 writestruct(wd, DATA, "BoidSettings", 1, part->boids);
845
846                                 for(; state; state=state->next)
847                                         write_boid_state(wd, state);
848                         }
849                         if(part->fluid && part->phystype == PART_PHYS_FLUID){
850                                 writestruct(wd, DATA, "SPHFluidSettings", 1, part->fluid); 
851                         }
852
853                         for(a=0; a<MAX_MTEX; a++) {
854                                 if(part->mtex[a]) writestruct(wd, DATA, "MTex", 1, part->mtex[a]);
855                         }
856                 }
857                 part= part->id.next;
858         }
859 }
860 static void write_particlesystems(WriteData *wd, ListBase *particles)
861 {
862         ParticleSystem *psys= particles->first;
863         ParticleTarget *pt;
864         int a;
865
866         for(; psys; psys=psys->next) {
867                 writestruct(wd, DATA, "ParticleSystem", 1, psys);
868
869                 if(psys->particles) {
870                         writestruct(wd, DATA, "ParticleData", psys->totpart ,psys->particles);
871
872                         if(psys->particles->hair) {
873                                 ParticleData *pa = psys->particles;
874
875                                 for(a=0; a<psys->totpart; a++, pa++)
876                                         writestruct(wd, DATA, "HairKey", pa->totkey, pa->hair);
877                         }
878
879                         if(psys->particles->boid && psys->part->phystype == PART_PHYS_BOIDS)
880                                 writestruct(wd, DATA, "BoidParticle", psys->totpart, psys->particles->boid);
881
882                         if(psys->part->fluid && psys->part->phystype == PART_PHYS_FLUID && (psys->part->fluid->flag & SPH_VISCOELASTIC_SPRINGS))
883                                 writestruct(wd, DATA, "ParticleSpring", psys->tot_fluidsprings, psys->fluid_springs);
884                 }
885                 pt = psys->targets.first;
886                 for(; pt; pt=pt->next)
887                         writestruct(wd, DATA, "ParticleTarget", 1, pt);
888
889                 if(psys->child) writestruct(wd, DATA, "ChildParticle", psys->totchild ,psys->child);
890
891                 if(psys->clmd) {
892                         writestruct(wd, DATA, "ClothModifierData", 1, psys->clmd);
893                         writestruct(wd, DATA, "ClothSimSettings", 1, psys->clmd->sim_parms);
894                         writestruct(wd, DATA, "ClothCollSettings", 1, psys->clmd->coll_parms);
895                 }
896                 
897                 write_pointcaches(wd, &psys->ptcaches);
898         }
899 }
900
901 static void write_properties(WriteData *wd, ListBase *lb)
902 {
903         bProperty *prop;
904
905         prop= lb->first;
906         while(prop) {
907                 writestruct(wd, DATA, "bProperty", 1, prop);
908
909                 if(prop->poin && prop->poin != &prop->data)
910                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
911
912                 prop= prop->next;
913         }
914 }
915
916 static void write_sensors(WriteData *wd, ListBase *lb)
917 {
918         bSensor *sens;
919
920         sens= lb->first;
921         while(sens) {
922                 writestruct(wd, DATA, "bSensor", 1, sens);
923
924                 writedata(wd, DATA, sizeof(void *)*sens->totlinks, sens->links);
925
926                 switch(sens->type) {
927                 case SENS_NEAR:
928                         writestruct(wd, DATA, "bNearSensor", 1, sens->data);
929                         break;
930                 case SENS_MOUSE:
931                         writestruct(wd, DATA, "bMouseSensor", 1, sens->data);
932                         break;
933                 case SENS_TOUCH:
934                         writestruct(wd, DATA, "bTouchSensor", 1, sens->data);
935                         break;
936                 case SENS_KEYBOARD:
937                         writestruct(wd, DATA, "bKeyboardSensor", 1, sens->data);
938                         break;
939                 case SENS_PROPERTY:
940                         writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
941                         break;
942                 case SENS_ARMATURE:
943                         writestruct(wd, DATA, "bArmatureSensor", 1, sens->data);
944                         break;
945                 case SENS_ACTUATOR:
946                         writestruct(wd, DATA, "bActuatorSensor", 1, sens->data);
947                         break;
948                 case SENS_DELAY:
949                         writestruct(wd, DATA, "bDelaySensor", 1, sens->data);
950                         break;
951                 case SENS_COLLISION:
952                         writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
953                         break;
954                 case SENS_RADAR:
955                         writestruct(wd, DATA, "bRadarSensor", 1, sens->data);
956                         break;
957                 case SENS_RANDOM:
958                         writestruct(wd, DATA, "bRandomSensor", 1, sens->data);
959                         break;
960                 case SENS_RAY:
961                         writestruct(wd, DATA, "bRaySensor", 1, sens->data);
962                         break;
963                 case SENS_MESSAGE:
964                         writestruct(wd, DATA, "bMessageSensor", 1, sens->data);
965                         break;
966                 case SENS_JOYSTICK:
967                         writestruct(wd, DATA, "bJoystickSensor", 1, sens->data);
968                         break;
969                 default:
970                         ; /* error: don't know how to write this file */
971                 }
972
973                 sens= sens->next;
974         }
975 }
976
977 static void write_controllers(WriteData *wd, ListBase *lb)
978 {
979         bController *cont;
980
981         cont= lb->first;
982         while(cont) {
983                 writestruct(wd, DATA, "bController", 1, cont);
984
985                 writedata(wd, DATA, sizeof(void *)*cont->totlinks, cont->links);
986
987                 switch(cont->type) {
988                 case CONT_EXPRESSION:
989                         writestruct(wd, DATA, "bExpressionCont", 1, cont->data);
990                         break;
991                 case CONT_PYTHON:
992                         writestruct(wd, DATA, "bPythonCont", 1, cont->data);
993                         break;
994                 default:
995                         ; /* error: don't know how to write this file */
996                 }
997
998                 cont= cont->next;
999         }
1000 }
1001
1002 static void write_actuators(WriteData *wd, ListBase *lb)
1003 {
1004         bActuator *act;
1005
1006         act= lb->first;
1007         while(act) {
1008                 writestruct(wd, DATA, "bActuator", 1, act);
1009
1010                 switch(act->type) {
1011                 case ACT_ACTION:
1012                 case ACT_SHAPEACTION:
1013                         writestruct(wd, DATA, "bActionActuator", 1, act->data);
1014                         break;
1015                 case ACT_SOUND:
1016                         writestruct(wd, DATA, "bSoundActuator", 1, act->data);
1017                         break;
1018                 case ACT_OBJECT:
1019                         writestruct(wd, DATA, "bObjectActuator", 1, act->data);
1020                         break;
1021                 case ACT_IPO:
1022                         writestruct(wd, DATA, "bIpoActuator", 1, act->data);
1023                         break;
1024                 case ACT_PROPERTY:
1025                         writestruct(wd, DATA, "bPropertyActuator", 1, act->data);
1026                         break;
1027                 case ACT_CAMERA:
1028                         writestruct(wd, DATA, "bCameraActuator", 1, act->data);
1029                         break;
1030                 case ACT_CONSTRAINT:
1031                         writestruct(wd, DATA, "bConstraintActuator", 1, act->data);
1032                         break;
1033                 case ACT_EDIT_OBJECT:
1034                         writestruct(wd, DATA, "bEditObjectActuator", 1, act->data);
1035                         break;
1036                 case ACT_SCENE:
1037                         writestruct(wd, DATA, "bSceneActuator", 1, act->data);
1038                         break;
1039                 case ACT_GROUP:
1040                         writestruct(wd, DATA, "bGroupActuator", 1, act->data);
1041                         break;
1042                 case ACT_RANDOM:
1043                         writestruct(wd, DATA, "bRandomActuator", 1, act->data);
1044                         break;
1045                 case ACT_MESSAGE:
1046                         writestruct(wd, DATA, "bMessageActuator", 1, act->data);
1047                         break;
1048                 case ACT_GAME:
1049                         writestruct(wd, DATA, "bGameActuator", 1, act->data);
1050                         break;
1051                 case ACT_VISIBILITY:
1052                         writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
1053                         break;
1054                 case ACT_2DFILTER:
1055                         writestruct(wd, DATA, "bTwoDFilterActuator", 1, act->data);
1056                         break;
1057                 case ACT_PARENT:
1058                         writestruct(wd, DATA, "bParentActuator", 1, act->data);
1059                         break;
1060                 case ACT_STATE:
1061                         writestruct(wd, DATA, "bStateActuator", 1, act->data);
1062                         break;
1063                 case ACT_ARMATURE:
1064                         writestruct(wd, DATA, "bArmatureActuator", 1, act->data);
1065                         break;
1066                 default:
1067                         ; /* error: don't know how to write this file */
1068                 }
1069
1070                 act= act->next;
1071         }
1072 }
1073
1074 static void write_motionpath(WriteData *wd, bMotionPath *mpath)
1075 {
1076         /* sanity checks */
1077         if (mpath == NULL)
1078                 return;
1079         
1080         /* firstly, just write the motionpath struct */
1081         writestruct(wd, DATA, "bMotionPath", 1, mpath);
1082         
1083         /* now write the array of data */
1084         writestruct(wd, DATA, "bMotionPathVert", mpath->length, mpath->points);
1085 }
1086
1087 static void write_constraints(WriteData *wd, ListBase *conlist)
1088 {
1089         bConstraint *con;
1090
1091         for (con=conlist->first; con; con=con->next) {
1092                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1093                 
1094                 /* Write the specific data */
1095                 if (cti && con->data) {
1096                         /* firstly, just write the plain con->data struct */
1097                         writestruct(wd, DATA, cti->structName, 1, con->data);
1098                         
1099                         /* do any constraint specific stuff */
1100                         switch (con->type) {
1101                                 case CONSTRAINT_TYPE_PYTHON:
1102                                 {
1103                                         bPythonConstraint *data = (bPythonConstraint *)con->data;
1104                                         bConstraintTarget *ct;
1105                                         
1106                                         /* write targets */
1107                                         for (ct= data->targets.first; ct; ct= ct->next)
1108                                                 writestruct(wd, DATA, "bConstraintTarget", 1, ct);
1109                                         
1110                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1111                                          of library blocks that implement this.*/
1112                                         IDP_WriteProperty(data->prop, wd);
1113                                 }
1114                                         break;
1115                                 case CONSTRAINT_TYPE_SPLINEIK: 
1116                                 {
1117                                         bSplineIKConstraint *data= (bSplineIKConstraint*)con->data;
1118                                         
1119                                         /* write points array */
1120                                         writedata(wd, DATA, sizeof(float)*(data->numpoints), data->points);
1121                                 }
1122                                         break;
1123                         }
1124                 }
1125                 
1126                 /* Write the constraint */
1127                 writestruct(wd, DATA, "bConstraint", 1, con);
1128         }
1129 }
1130
1131 static void write_pose(WriteData *wd, bPose *pose)
1132 {
1133         bPoseChannel *chan;
1134         bActionGroup *grp;
1135
1136         /* Write each channel */
1137         if (!pose)
1138                 return;
1139
1140         /* Write channels */
1141         for (chan=pose->chanbase.first; chan; chan=chan->next) {
1142                 /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1143                  of library blocks that implement this.*/
1144                 if (chan->prop)
1145                         IDP_WriteProperty(chan->prop, wd);
1146                 
1147                 write_constraints(wd, &chan->constraints);
1148                 
1149                 write_motionpath(wd, chan->mpath);
1150                 
1151                 /* prevent crashes with autosave, when a bone duplicated in editmode has not yet been assigned to its posechannel */
1152                 if (chan->bone) 
1153                         chan->selectflag= chan->bone->flag & BONE_SELECTED; /* gets restored on read, for library armatures */
1154                 
1155                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
1156         }
1157         
1158         /* Write groups */
1159         for (grp=pose->agroups.first; grp; grp=grp->next) 
1160                 writestruct(wd, DATA, "bActionGroup", 1, grp);
1161
1162         /* write IK param */
1163         if (pose->ikparam) {
1164                 char *structname = (char *)get_ikparam_name(pose);
1165                 if (structname)
1166                         writestruct(wd, DATA, structname, 1, pose->ikparam);
1167         }
1168
1169         /* Write this pose */
1170         writestruct(wd, DATA, "bPose", 1, pose);
1171
1172 }
1173
1174 static void write_defgroups(WriteData *wd, ListBase *defbase)
1175 {
1176         bDeformGroup    *defgroup;
1177
1178         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
1179                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
1180 }
1181
1182 static void write_modifiers(WriteData *wd, ListBase *modbase)
1183 {
1184         ModifierData *md;
1185
1186         if (modbase == NULL) return;
1187         for (md=modbase->first; md; md= md->next) {
1188                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1189                 if (mti == NULL) return;
1190                 
1191                 writestruct(wd, DATA, mti->structName, 1, md);
1192                         
1193                 if (md->type==eModifierType_Hook) {
1194                         HookModifierData *hmd = (HookModifierData*) md;
1195                         
1196                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
1197                 }
1198                 else if(md->type==eModifierType_Cloth) {
1199                         ClothModifierData *clmd = (ClothModifierData*) md;
1200                         
1201                         writestruct(wd, DATA, "ClothSimSettings", 1, clmd->sim_parms);
1202                         writestruct(wd, DATA, "ClothCollSettings", 1, clmd->coll_parms);
1203                         writestruct(wd, DATA, "EffectorWeights", 1, clmd->sim_parms->effector_weights);
1204                         write_pointcaches(wd, &clmd->ptcaches);
1205                 } 
1206                 else if(md->type==eModifierType_Smoke) {
1207                         SmokeModifierData *smd = (SmokeModifierData*) md;
1208                         
1209                         if(smd->type & MOD_SMOKE_TYPE_DOMAIN)
1210                         {
1211                                 if(smd->domain)
1212                                 {
1213                                         write_pointcaches(wd, &(smd->domain->ptcaches[0]));
1214
1215                                         /* create fake pointcache so that old blender versions can read it */
1216                                         smd->domain->point_cache[1] = BKE_ptcache_add(&smd->domain->ptcaches[1]);
1217                                         smd->domain->point_cache[1]->flag |= PTCACHE_DISK_CACHE;
1218                                         smd->domain->point_cache[1]->step = 1;
1219
1220                                         write_pointcaches(wd, &(smd->domain->ptcaches[1]));
1221                                 }
1222                                 
1223                                 writestruct(wd, DATA, "SmokeDomainSettings", 1, smd->domain);
1224
1225                                 if(smd->domain) {
1226                                         /* cleanup the fake pointcache */
1227                                         BKE_ptcache_free_list(&smd->domain->ptcaches[1]);
1228                                         smd->domain->point_cache[1] = NULL;
1229                                         
1230                                         writestruct(wd, DATA, "EffectorWeights", 1, smd->domain->effector_weights);
1231                                 }
1232                         }
1233                         else if(smd->type & MOD_SMOKE_TYPE_FLOW)
1234                                 writestruct(wd, DATA, "SmokeFlowSettings", 1, smd->flow);
1235                         else if(smd->type & MOD_SMOKE_TYPE_COLL)
1236                                 writestruct(wd, DATA, "SmokeCollSettings", 1, smd->coll);
1237                 } 
1238                 else if(md->type==eModifierType_Fluidsim) {
1239                         FluidsimModifierData *fluidmd = (FluidsimModifierData*) md;
1240                         
1241                         writestruct(wd, DATA, "FluidsimSettings", 1, fluidmd->fss);
1242                 } 
1243                 else if (md->type==eModifierType_Collision) {
1244                         
1245                         /*
1246                         CollisionModifierData *collmd = (CollisionModifierData*) md;
1247                         // TODO: CollisionModifier should use pointcache 
1248                         // + have proper reset events before enabling this
1249                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->x);
1250                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->xnew);
1251                         writestruct(wd, DATA, "MFace", collmd->numfaces, collmd->mfaces);
1252                         */
1253                 }
1254                 else if (md->type==eModifierType_MeshDeform) {
1255                         MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
1256                         int size = mmd->dyngridsize;
1257
1258                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->bindinfluences);
1259                         writedata(wd, DATA, sizeof(int)*(mmd->totvert+1), mmd->bindoffsets);
1260                         writedata(wd, DATA, sizeof(float)*3*mmd->totcagevert,
1261                                 mmd->bindcagecos);
1262                         writestruct(wd, DATA, "MDefCell", size*size*size, mmd->dyngrid);
1263                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->dyninfluences);
1264                         writedata(wd, DATA, sizeof(int)*mmd->totvert, mmd->dynverts);
1265                 }
1266         }
1267 }
1268
1269 static void write_objects(WriteData *wd, ListBase *idbase)
1270 {
1271         Object *ob;
1272         
1273         ob= idbase->first;
1274         while(ob) {
1275                 if(ob->id.us>0 || wd->current) {
1276                         /* write LibData */
1277                         writestruct(wd, ID_OB, "Object", 1, ob);
1278                         
1279                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1280                           of library blocks that implement this.*/
1281                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
1282                         
1283                         if (ob->adt) write_animdata(wd, ob->adt);
1284                         
1285                         /* direct data */
1286                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
1287                         writedata(wd, DATA, sizeof(char)*ob->totcol, ob->matbits);
1288                         /* write_effects(wd, &ob->effect); */ /* not used anymore */
1289                         write_properties(wd, &ob->prop);
1290                         write_sensors(wd, &ob->sensors);
1291                         write_controllers(wd, &ob->controllers);
1292                         write_actuators(wd, &ob->actuators);
1293
1294                         if (ob->type == OB_ARMATURE) {
1295                                 bArmature *arm = ob->data;
1296                                 if (arm && ob->pose && arm->act_bone) {
1297                                         BLI_strncpy(ob->pose->proxy_act_bone, arm->act_bone->name, sizeof(ob->pose->proxy_act_bone));
1298                                 }
1299                         }
1300
1301                         write_pose(wd, ob->pose);
1302                         write_defgroups(wd, &ob->defbase);
1303                         write_constraints(wd, &ob->constraints);
1304                         write_motionpath(wd, ob->mpath);
1305                         
1306                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
1307                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
1308                         if(ob->soft) {
1309                                 write_pointcaches(wd, &ob->soft->ptcaches);
1310                                 writestruct(wd, DATA, "EffectorWeights", 1, ob->soft->effector_weights);
1311                         }
1312                         writestruct(wd, DATA, "BulletSoftBody", 1, ob->bsoft);
1313                         
1314                         write_particlesystems(wd, &ob->particlesystem);
1315                         write_modifiers(wd, &ob->modifiers);
1316                 }
1317                 ob= ob->id.next;
1318         }
1319
1320         /* flush helps the compression for undo-save */
1321         mywrite(wd, MYWRITE_FLUSH, 0);
1322 }
1323
1324
1325 static void write_vfonts(WriteData *wd, ListBase *idbase)
1326 {
1327         VFont *vf;
1328         PackedFile * pf;
1329
1330         vf= idbase->first;
1331         while(vf) {
1332                 if(vf->id.us>0 || wd->current) {
1333                         /* write LibData */
1334                         writestruct(wd, ID_VF, "VFont", 1, vf);
1335                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
1336
1337                         /* direct data */
1338
1339                         if (vf->packedfile) {
1340                                 pf = vf->packedfile;
1341                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1342                                 writedata(wd, DATA, pf->size, pf->data);
1343                         }
1344                 }
1345
1346                 vf= vf->id.next;
1347         }
1348 }
1349
1350
1351 static void write_keys(WriteData *wd, ListBase *idbase)
1352 {
1353         Key *key;
1354         KeyBlock *kb;
1355
1356         key= idbase->first;
1357         while(key) {
1358                 if(key->id.us>0 || wd->current) {
1359                         /* write LibData */
1360                         writestruct(wd, ID_KE, "Key", 1, key);
1361                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
1362                         
1363                         if (key->adt) write_animdata(wd, key->adt);
1364                         
1365                         /* direct data */
1366                         kb= key->block.first;
1367                         while(kb) {
1368                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
1369                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
1370                                 kb= kb->next;
1371                         }
1372                 }
1373
1374                 key= key->id.next;
1375         }
1376         /* flush helps the compression for undo-save */
1377         mywrite(wd, MYWRITE_FLUSH, 0);
1378 }
1379
1380 static void write_cameras(WriteData *wd, ListBase *idbase)
1381 {
1382         Camera *cam;
1383
1384         cam= idbase->first;
1385         while(cam) {
1386                 if(cam->id.us>0 || wd->current) {
1387                         /* write LibData */
1388                         writestruct(wd, ID_CA, "Camera", 1, cam);
1389                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
1390                         
1391                         if (cam->adt) write_animdata(wd, cam->adt);
1392                 }
1393
1394                 cam= cam->id.next;
1395         }
1396 }
1397
1398 static void write_mballs(WriteData *wd, ListBase *idbase)
1399 {
1400         MetaBall *mb;
1401         MetaElem *ml;
1402
1403         mb= idbase->first;
1404         while(mb) {
1405                 if(mb->id.us>0 || wd->current) {
1406                         /* write LibData */
1407                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
1408                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
1409
1410                         /* direct data */
1411                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
1412                         if (mb->adt) write_animdata(wd, mb->adt);
1413
1414                         ml= mb->elems.first;
1415                         while(ml) {
1416                                 writestruct(wd, DATA, "MetaElem", 1, ml);
1417                                 ml= ml->next;
1418                         }
1419                 }
1420                 mb= mb->id.next;
1421         }
1422 }
1423
1424 static int amount_of_chars(char *str)
1425 {
1426         // Since the data is saved as UTF-8 to the cu->str
1427         // The cu->len is not same as the strlen(cu->str)
1428         return strlen(str);
1429 }
1430
1431 static void write_curves(WriteData *wd, ListBase *idbase)
1432 {
1433         Curve *cu;
1434         Nurb *nu;
1435
1436         cu= idbase->first;
1437         while(cu) {
1438                 if(cu->id.us>0 || wd->current) {
1439                         /* write LibData */
1440                         writestruct(wd, ID_CU, "Curve", 1, cu);
1441                         
1442                         /* direct data */
1443                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
1444                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
1445                         if (cu->adt) write_animdata(wd, cu->adt);
1446                         
1447                         if(cu->vfont) {
1448                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1449                                 writestruct(wd, DATA, "CharInfo", cu->len+1, cu->strinfo);
1450                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);                           
1451                         }
1452                         else {
1453                                 /* is also the order of reading */
1454                                 nu= cu->nurb.first;
1455                                 while(nu) {
1456                                         writestruct(wd, DATA, "Nurb", 1, nu);
1457                                         nu= nu->next;
1458                                 }
1459                                 nu= cu->nurb.first;
1460                                 while(nu) {
1461                                         if(nu->type == CU_BEZIER)
1462                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1463                                         else {
1464                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1465                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1466                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1467                                         }
1468                                         nu= nu->next;
1469                                 }
1470                         }
1471                 }
1472                 cu= cu->id.next;
1473         }
1474
1475         /* flush helps the compression for undo-save */
1476         mywrite(wd, MYWRITE_FLUSH, 0);
1477 }
1478
1479 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1480 {
1481         if (dvlist) {
1482                 int i;
1483                 
1484                 /* Write the dvert list */
1485                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1486                 
1487                 /* Write deformation data for each dvert */
1488                 for (i=0; i<count; i++) {
1489                         if (dvlist[i].dw)
1490                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1491                 }
1492         }
1493 }
1494
1495 static void write_mdisps(WriteData *wd, int count, MDisps *mdlist, int external)
1496 {
1497         if(mdlist) {
1498                 int i;
1499                 
1500                 writestruct(wd, DATA, "MDisps", count, mdlist);
1501                 if(!external) {
1502                         for(i = 0; i < count; ++i) {
1503                                 if(mdlist[i].disps)
1504                                         writedata(wd, DATA, sizeof(float)*3*mdlist[i].totdisp, mdlist[i].disps);
1505                         }
1506                 }
1507         }
1508 }
1509
1510 static void write_customdata(WriteData *wd, ID *id, int count, CustomData *data, int partial_type, int partial_count)
1511 {
1512         int i;
1513
1514         /* write external customdata (not for undo) */
1515         if(data->external && !wd->current)
1516                 CustomData_external_write(data, id, CD_MASK_MESH, count, 0);
1517
1518         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1519
1520         for (i=0; i<data->totlayer; i++) {
1521                 CustomDataLayer *layer= &data->layers[i];
1522                 const char *structname;
1523                 int structnum, datasize;
1524
1525                 if (layer->type == CD_MDEFORMVERT) {
1526                         /* layer types that allocate own memory need special handling */
1527                         write_dverts(wd, count, layer->data);
1528                 }
1529                 else if (layer->type == CD_MDISPS) {
1530                         write_mdisps(wd, count, layer->data, layer->flag & CD_FLAG_EXTERNAL);
1531                 }
1532                 else {
1533                         CustomData_file_write_info(layer->type, &structname, &structnum);
1534                         if (structnum) {
1535                                 /* when using partial visibility, the MEdge and MFace layers
1536                                    are smaller than the original, so their type and count is
1537                                    passed to make this work */
1538                                 if (layer->type != partial_type) datasize= structnum*count;
1539                                 else datasize= structnum*partial_count;
1540
1541                                 writestruct(wd, DATA, structname, datasize, layer->data);
1542                         }
1543                         else
1544                                 printf("error: this CustomDataLayer must not be written to file\n");
1545                 }
1546         }
1547
1548         if(data->external)
1549                 writestruct(wd, DATA, "CustomDataExternal", 1, data->external);
1550 }
1551
1552 static void write_meshs(WriteData *wd, ListBase *idbase)
1553 {
1554         Mesh *mesh;
1555
1556         mesh= idbase->first;
1557         while(mesh) {
1558                 if(mesh->id.us>0 || wd->current) {
1559                         /* write LibData */
1560                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
1561
1562                         /* direct data */
1563                         if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1564                         if (mesh->adt) write_animdata(wd, mesh->adt);
1565
1566                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1567
1568                         if(mesh->pv) {
1569                                 write_customdata(wd, &mesh->id, mesh->pv->totvert, &mesh->vdata, -1, 0);
1570                                 write_customdata(wd, &mesh->id, mesh->pv->totedge, &mesh->edata,
1571                                         CD_MEDGE, mesh->totedge);
1572                                 write_customdata(wd, &mesh->id, mesh->pv->totface, &mesh->fdata,
1573                                         CD_MFACE, mesh->totface);
1574                         }
1575                         else {
1576                                 write_customdata(wd, &mesh->id, mesh->totvert, &mesh->vdata, -1, 0);
1577                                 write_customdata(wd, &mesh->id, mesh->totedge, &mesh->edata, -1, 0);
1578                                 write_customdata(wd, &mesh->id, mesh->totface, &mesh->fdata, -1, 0);
1579                         }
1580
1581                         /* PMV data */
1582                         if(mesh->pv) {
1583                                 writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
1584                                 writedata(wd, DATA, sizeof(unsigned int)*mesh->pv->totvert, mesh->pv->vert_map);
1585                                 writedata(wd, DATA, sizeof(int)*mesh->pv->totedge, mesh->pv->edge_map);
1586                                 writestruct(wd, DATA, "MFace", mesh->pv->totface, mesh->pv->old_faces);
1587                                 writestruct(wd, DATA, "MEdge", mesh->pv->totedge, mesh->pv->old_edges);
1588                         }
1589                 }
1590                 mesh= mesh->id.next;
1591         }
1592 }
1593
1594 static void write_lattices(WriteData *wd, ListBase *idbase)
1595 {
1596         Lattice *lt;
1597         
1598         lt= idbase->first;
1599         while(lt) {
1600                 if(lt->id.us>0 || wd->current) {
1601                         /* write LibData */
1602                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1603                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1604                         
1605                         /* write animdata */
1606                         if (lt->adt) write_animdata(wd, lt->adt);
1607                         
1608                         /* direct data */
1609                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1610                         
1611                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1612                         
1613                 }
1614                 lt= lt->id.next;
1615         }
1616 }
1617
1618 static void write_previews(WriteData *wd, PreviewImage *prv)
1619 {
1620         if (prv) {
1621                 short w = prv->w[1];
1622                 short h = prv->h[1];
1623                 unsigned int *rect = prv->rect[1];
1624                 /* don't write out large previews if not requested */
1625                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1626                         prv->w[1] = 0;
1627                         prv->h[1] = 0;
1628                         prv->rect[1] = NULL;
1629                 }
1630                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1631                 if (prv->rect[0]) writedata(wd, DATA, prv->w[0]*prv->h[0]*sizeof(unsigned int), prv->rect[0]);
1632                 if (prv->rect[1]) writedata(wd, DATA, prv->w[1]*prv->h[1]*sizeof(unsigned int), prv->rect[1]);
1633
1634                 /* restore preview, we still want to keep it in memory even if not saved to file */
1635                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1636                         prv->w[1] = w;
1637                         prv->h[1] = h;
1638                         prv->rect[1] = rect;
1639                 }
1640         }
1641 }
1642
1643 static void write_images(WriteData *wd, ListBase *idbase)
1644 {
1645         Image *ima;
1646         PackedFile * pf;
1647
1648
1649         ima= idbase->first;
1650         while(ima) {
1651                 if(ima->id.us>0 || wd->current) {
1652                         /* write LibData */
1653                         writestruct(wd, ID_IM, "Image", 1, ima);
1654                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1655
1656                         if (ima->packedfile) {
1657                                 pf = ima->packedfile;
1658                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1659                                 writedata(wd, DATA, pf->size, pf->data);
1660                         }
1661
1662                         write_previews(wd, ima->preview);
1663                 }
1664                 ima= ima->id.next;
1665         }
1666         /* flush helps the compression for undo-save */
1667         mywrite(wd, MYWRITE_FLUSH, 0);
1668 }
1669
1670 static void write_textures(WriteData *wd, ListBase *idbase)
1671 {
1672         Tex *tex;
1673
1674         tex= idbase->first;
1675         while(tex) {
1676                 if(tex->id.us>0 || wd->current) {
1677                         /* write LibData */
1678                         writestruct(wd, ID_TE, "Tex", 1, tex);
1679                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1680
1681                         if (tex->adt) write_animdata(wd, tex->adt);
1682
1683                         /* direct data */
1684                         if(tex->type == TEX_PLUGIN && tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1685                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1686                         if(tex->type == TEX_ENVMAP && tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1687                         if(tex->type == TEX_POINTDENSITY && tex->pd) {
1688                                 writestruct(wd, DATA, "PointDensity", 1, tex->pd);
1689                                 if(tex->pd->coba) writestruct(wd, DATA, "ColorBand", 1, tex->pd->coba);
1690                         }
1691                         if(tex->type == TEX_VOXELDATA && tex->vd) writestruct(wd, DATA, "VoxelData", 1, tex->vd);
1692                         
1693                         /* nodetree is integral part of texture, no libdata */
1694                         if(tex->nodetree) {
1695                                 writestruct(wd, DATA, "bNodeTree", 1, tex->nodetree);
1696                                 write_nodetree(wd, tex->nodetree);
1697                         }
1698                         
1699                         write_previews(wd, tex->preview);
1700                 }
1701                 tex= tex->id.next;
1702         }
1703
1704         /* flush helps the compression for undo-save */
1705         mywrite(wd, MYWRITE_FLUSH, 0);
1706 }
1707
1708 static void write_materials(WriteData *wd, ListBase *idbase)
1709 {
1710         Material *ma;
1711         int a;
1712
1713         ma= idbase->first;
1714         while(ma) {
1715                 if(ma->id.us>0 || wd->current) {
1716                         /* write LibData */
1717                         writestruct(wd, ID_MA, "Material", 1, ma);
1718                         
1719                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1720                           of library blocks that implement this.*/
1721                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1722                           set yet :) */
1723                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1724                         
1725                         if (ma->adt) write_animdata(wd, ma->adt);
1726
1727                         for(a=0; a<MAX_MTEX; a++) {
1728                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1729                         }
1730                         
1731                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1732                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1733                         
1734                         /* nodetree is integral part of material, no libdata */
1735                         if(ma->nodetree) {
1736                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1737                                 write_nodetree(wd, ma->nodetree);
1738                         }
1739
1740                         write_previews(wd, ma->preview);                        
1741                 }
1742                 ma= ma->id.next;
1743         }
1744 }
1745
1746 static void write_worlds(WriteData *wd, ListBase *idbase)
1747 {
1748         World *wrld;
1749         int a;
1750
1751         wrld= idbase->first;
1752         while(wrld) {
1753                 if(wrld->id.us>0 || wd->current) {
1754                         /* write LibData */
1755                         writestruct(wd, ID_WO, "World", 1, wrld);
1756                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1757                         
1758                         if (wrld->adt) write_animdata(wd, wrld->adt);
1759                         
1760                         for(a=0; a<MAX_MTEX; a++) {
1761                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1762                         }
1763                         
1764                         write_previews(wd, wrld->preview);
1765                 }
1766                 wrld= wrld->id.next;
1767         }
1768 }
1769
1770 static void write_lamps(WriteData *wd, ListBase *idbase)
1771 {
1772         Lamp *la;
1773         int a;
1774
1775         la= idbase->first;
1776         while(la) {
1777                 if(la->id.us>0 || wd->current) {
1778                         /* write LibData */
1779                         writestruct(wd, ID_LA, "Lamp", 1, la);
1780                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1781                         
1782                         if (la->adt) write_animdata(wd, la->adt);
1783                         
1784                         /* direct data */
1785                         for(a=0; a<MAX_MTEX; a++) {
1786                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1787                         }
1788                         
1789                         if(la->curfalloff)
1790                                 write_curvemapping(wd, la->curfalloff); 
1791                         
1792                         write_previews(wd, la->preview);
1793                         
1794                 }
1795                 la= la->id.next;
1796         }
1797 }
1798
1799
1800 static void write_scenes(WriteData *wd, ListBase *scebase)
1801 {
1802         Scene *sce;
1803         Base *base;
1804         Editing *ed;
1805         Sequence *seq;
1806         MetaStack *ms;
1807         Strip *strip;
1808         TimeMarker *marker;
1809         TransformOrientation *ts;
1810         SceneRenderLayer *srl;
1811         ToolSettings *tos;
1812         
1813         sce= scebase->first;
1814         while(sce) {
1815                 /* write LibData */
1816                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1817                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1818                 
1819                 if (sce->adt) write_animdata(wd, sce->adt);
1820                 write_keyingsets(wd, &sce->keyingsets);
1821                 
1822                 /* direct data */
1823                 base= sce->base.first;
1824                 while(base) {
1825                         writestruct(wd, DATA, "Base", 1, base);
1826                         base= base->next;
1827                 }
1828                 
1829                 tos = sce->toolsettings;
1830                 writestruct(wd, DATA, "ToolSettings", 1, tos);
1831                 if(tos->vpaint) {
1832                         writestruct(wd, DATA, "VPaint", 1, tos->vpaint);
1833                 }
1834                 if(tos->wpaint) {
1835                         writestruct(wd, DATA, "VPaint", 1, tos->wpaint);
1836                 }
1837                 if(tos->sculpt) {
1838                         writestruct(wd, DATA, "Sculpt", 1, tos->sculpt);
1839                 }
1840
1841                 // write_paint(wd, &tos->imapaint.paint);
1842
1843                 ed= sce->ed;
1844                 if(ed) {
1845                         writestruct(wd, DATA, "Editing", 1, ed);
1846                         
1847                         /* reset write flags too */
1848                         
1849                         SEQ_BEGIN(ed, seq) {
1850                                 if(seq->strip) seq->strip->done= 0;
1851                                 writestruct(wd, DATA, "Sequence", 1, seq);
1852                         }
1853                         SEQ_END
1854                         
1855                         SEQ_BEGIN(ed, seq) {
1856                                 if(seq->strip && seq->strip->done==0) {
1857                                         /* write strip with 'done' at 0 because readfile */
1858                                         
1859                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1860                                         if(seq->effectdata) {
1861                                                 switch(seq->type){
1862                                                 case SEQ_COLOR:
1863                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
1864                                                         break;
1865                                                 case SEQ_SPEED:
1866                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
1867                                                         break;
1868                                                 case SEQ_WIPE:
1869                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1870                                                         break;
1871                                                 case SEQ_GLOW:
1872                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1873                                                         break;
1874                                                 case SEQ_TRANSFORM:
1875                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
1876                                                         break;
1877                                                 }
1878                                         }
1879                                         
1880                                         strip= seq->strip;
1881                                         writestruct(wd, DATA, "Strip", 1, strip);
1882                                         if(seq->flag & SEQ_USE_CROP && strip->crop) {
1883                                                 writestruct(wd, DATA, "StripCrop", 1, strip->crop);
1884                                         }
1885                                         if(seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
1886                                                 writestruct(wd, DATA, "StripTransform", 1, strip->transform);
1887                                         }
1888                                         if(seq->flag & SEQ_USE_PROXY && strip->proxy) {
1889                                                 writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
1890                                         }
1891                                         if(seq->flag & SEQ_USE_COLOR_BALANCE && strip->color_balance) {
1892                                                 writestruct(wd, DATA, "StripColorBalance", 1, strip->color_balance);
1893                                         }
1894                                         if(seq->type==SEQ_IMAGE)
1895                                                 writestruct(wd, DATA, "StripElem", MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem), strip->stripdata);
1896                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
1897                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1898                                         
1899                                         strip->done= 1;
1900                                 }
1901                         }
1902                         SEQ_END
1903                                 
1904                         /* new; meta stack too, even when its nasty restore code */
1905                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1906                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1907                         }
1908                 }
1909                 
1910                 if (sce->r.avicodecdata) {
1911                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1912                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1913                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1914                 }
1915
1916                 if (sce->r.qtcodecdata) {
1917                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1918                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1919                 }
1920                 if (sce->r.ffcodecdata.properties) {
1921                         IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
1922                 }
1923
1924                 /* writing dynamic list of TimeMarkers to the blend file */
1925                 for(marker= sce->markers.first; marker; marker= marker->next)
1926                         writestruct(wd, DATA, "TimeMarker", 1, marker);
1927                 
1928                 /* writing dynamic list of TransformOrientations to the blend file */
1929                 for(ts = sce->transform_spaces.first; ts; ts = ts->next)
1930                         writestruct(wd, DATA, "TransformOrientation", 1, ts);
1931                 
1932                 for(srl= sce->r.layers.first; srl; srl= srl->next)
1933                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
1934                 
1935                 if(sce->nodetree) {
1936                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
1937                         write_nodetree(wd, sce->nodetree);
1938                 }
1939                 
1940                 sce= sce->id.next;
1941         }
1942         /* flush helps the compression for undo-save */
1943         mywrite(wd, MYWRITE_FLUSH, 0);
1944 }
1945
1946 static void write_gpencils(WriteData *wd, ListBase *lb)
1947 {
1948         bGPdata *gpd;
1949         bGPDlayer *gpl;
1950         bGPDframe *gpf;
1951         bGPDstroke *gps;
1952         
1953         for (gpd= lb->first; gpd; gpd= gpd->id.next) {
1954                 if (gpd->id.us>0 || wd->current) {
1955                         /* write gpd data block to file */
1956                         writestruct(wd, ID_GD, "bGPdata", 1, gpd);
1957                         
1958                         /* write grease-pencil layers to file */
1959                         for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
1960                                 writestruct(wd, DATA, "bGPDlayer", 1, gpl);
1961                                 
1962                                 /* write this layer's frames to file */
1963                                 for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
1964                                         writestruct(wd, DATA, "bGPDframe", 1, gpf);
1965                                         
1966                                         /* write strokes */
1967                                         for (gps= gpf->strokes.first; gps; gps= gps->next) {
1968                                                 writestruct(wd, DATA, "bGPDstroke", 1, gps);
1969                                                 writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);                               
1970                                         }
1971                                 }
1972                         }
1973                 }
1974         }
1975 }
1976
1977 static void write_windowmanagers(WriteData *wd, ListBase *lb)
1978 {
1979         wmWindowManager *wm;
1980         wmWindow *win;
1981         
1982         for(wm= lb->first; wm; wm= wm->id.next) {
1983                 writestruct(wd, ID_WM, "wmWindowManager", 1, wm);
1984                 
1985                 for(win= wm->windows.first; win; win= win->next)
1986                         writestruct(wd, DATA, "wmWindow", 1, win);
1987         }
1988 }
1989
1990 static void write_region(WriteData *wd, ARegion *ar, int spacetype)
1991 {       
1992         writestruct(wd, DATA, "ARegion", 1, ar);
1993         
1994         if(ar->regiondata) {
1995                 switch(spacetype) {
1996                         case SPACE_VIEW3D:
1997                                 if(ar->regiontype==RGN_TYPE_WINDOW) {
1998                                         RegionView3D *rv3d= ar->regiondata;
1999                                         writestruct(wd, DATA, "RegionView3D", 1, rv3d);
2000                                         
2001                                         if(rv3d->localvd)
2002                                                 writestruct(wd, DATA, "RegionView3D", 1, rv3d->localvd);
2003                                         if(rv3d->clipbb) 
2004                                                 writestruct(wd, DATA, "BoundBox", 1, rv3d->clipbb);
2005
2006                                 }
2007                                 else
2008                                         printf("regiondata write missing!\n");
2009                                 break;
2010                         default:
2011                                 printf("regiondata write missing!\n");
2012                 }
2013         }
2014 }
2015
2016 static void write_screens(WriteData *wd, ListBase *scrbase)
2017 {
2018         bScreen *sc;
2019         ScrArea *sa;
2020         ScrVert *sv;
2021         ScrEdge *se;
2022
2023         sc= scrbase->first;
2024         while(sc) {
2025                 
2026                 /* write LibData */
2027                 /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
2028                 writestruct(wd, ID_SCRN, "Screen", 1, sc);
2029                 if (sc->id.properties) 
2030                         IDP_WriteProperty(sc->id.properties, wd);
2031                 
2032                 /* direct data */
2033                 for(sv= sc->vertbase.first; sv; sv= sv->next)
2034                         writestruct(wd, DATA, "ScrVert", 1, sv);
2035                 
2036                 for(se= sc->edgebase.first; se; se= se->next) 
2037                         writestruct(wd, DATA, "ScrEdge", 1, se);
2038                 
2039                 for(sa= sc->areabase.first; sa; sa= sa->next) {
2040                         SpaceLink *sl;
2041                         Panel *pa;
2042                         ARegion *ar;
2043                         
2044                         writestruct(wd, DATA, "ScrArea", 1, sa);
2045                         
2046                         for(ar= sa->regionbase.first; ar; ar= ar->next) {
2047                                 write_region(wd, ar, sa->spacetype);
2048                                 
2049                                 for(pa= ar->panels.first; pa; pa= pa->next)
2050                                         writestruct(wd, DATA, "Panel", 1, pa);
2051                         }
2052                         
2053                         sl= sa->spacedata.first;
2054                         while(sl) {
2055                                 for(ar= sl->regionbase.first; ar; ar= ar->next)
2056                                         write_region(wd, ar, sl->spacetype);
2057                                 
2058                                 if(sl->spacetype==SPACE_VIEW3D) {
2059                                         View3D *v3d= (View3D *) sl;
2060                                         BGpic *bgpic;
2061                                         writestruct(wd, DATA, "View3D", 1, v3d);
2062                                         for (bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next)
2063                                                 writestruct(wd, DATA, "BGpic", 1, bgpic);
2064                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
2065                                 }
2066                                 else if(sl->spacetype==SPACE_IPO) {
2067                                         SpaceIpo *sipo= (SpaceIpo *)sl;
2068                                         ListBase tmpGhosts = sipo->ghostCurves;
2069                                         
2070                                         /* temporarily disable ghost curves when saving */
2071                                         sipo->ghostCurves.first= sipo->ghostCurves.last= NULL;
2072                                         
2073                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
2074                                         if(sipo->ads) writestruct(wd, DATA, "bDopeSheet", 1, sipo->ads);
2075                                         
2076                                         /* reenable ghost curves */
2077                                         sipo->ghostCurves= tmpGhosts;
2078                                 }
2079                                 else if(sl->spacetype==SPACE_BUTS) {
2080                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
2081                                 }
2082                                 else if(sl->spacetype==SPACE_FILE) {
2083                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
2084                                 }
2085                                 else if(sl->spacetype==SPACE_SEQ) {
2086                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
2087                                 }
2088                                 else if(sl->spacetype==SPACE_OUTLINER) {
2089                                         SpaceOops *so= (SpaceOops *)sl;
2090                                         
2091                                         writestruct(wd, DATA, "SpaceOops", 1, so);
2092
2093                                         /* outliner */
2094                                         if(so->treestore) {
2095                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
2096                                                 if(so->treestore->data)
2097                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
2098                                         }
2099                                 }
2100                                 else if(sl->spacetype==SPACE_IMAGE) {
2101                                         SpaceImage *sima= (SpaceImage *)sl;
2102                                         
2103                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
2104                                         if(sima->cumap)
2105                                                 write_curvemapping(wd, sima->cumap);
2106                                 }
2107                                 else if(sl->spacetype==SPACE_IMASEL) {
2108                                         // XXX: depreceated... do we still want to keep this?
2109                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
2110                                 }
2111                                 else if(sl->spacetype==SPACE_TEXT) {
2112                                         writestruct(wd, DATA, "SpaceText", 1, sl);
2113                                 }
2114                                 else if(sl->spacetype==SPACE_SCRIPT) {
2115                                         SpaceScript *sc = (SpaceScript*)sl;
2116                                         sc->but_refs = NULL;
2117                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
2118                                 }
2119                                 else if(sl->spacetype==SPACE_ACTION) {
2120                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
2121                                 }
2122                                 else if(sl->spacetype==SPACE_SOUND) {
2123                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
2124                                 }
2125                                 else if(sl->spacetype==SPACE_NLA){
2126                                         SpaceNla *snla= (SpaceNla *)sl;
2127                                         
2128                                         writestruct(wd, DATA, "SpaceNla", 1, snla);
2129                                         if(snla->ads) writestruct(wd, DATA, "bDopeSheet", 1, snla->ads);
2130                                 }
2131                                 else if(sl->spacetype==SPACE_TIME){
2132                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
2133                                 }
2134                                 else if(sl->spacetype==SPACE_NODE){
2135                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
2136                                 }
2137                                 else if(sl->spacetype==SPACE_LOGIC){
2138                                         writestruct(wd, DATA, "SpaceLogic", 1, sl);
2139                                 }
2140                                 else if(sl->spacetype==SPACE_CONSOLE) {
2141                                         SpaceConsole *con = (SpaceConsole*)sl;
2142                                         ConsoleLine *cl;
2143
2144                                         for (cl=con->history.first; cl; cl=cl->next) {
2145                                                 /* 'len_alloc' is invalid on write, set from 'len' on read */
2146                                                 writestruct(wd, DATA, "ConsoleLine", 1, cl);
2147                                                 writedata(wd, DATA, cl->len+1, cl->line);
2148                                         }
2149                                         writestruct(wd, DATA, "SpaceConsole", 1, sl);
2150
2151                                 }
2152                                 else if(sl->spacetype==SPACE_USERPREF) {
2153                                         writestruct(wd, DATA, "SpaceUserPref", 1, sl);
2154                                 }
2155
2156                                 sl= sl->next;
2157                         }
2158                 }
2159
2160                 sc= sc->id.next;
2161         }
2162 }
2163
2164 static void write_libraries(WriteData *wd, Main *main)
2165 {
2166         ListBase *lbarray[30];
2167         ID *id;
2168         int a, tot, foundone;
2169
2170         for(; main; main= main->next) {
2171
2172                 a=tot= set_listbasepointers(main, lbarray);
2173
2174                 /* test: is lib being used */
2175                 foundone= 0;
2176                 while(tot--) {
2177                         for(id= lbarray[tot]->first; id; id= id->next) {
2178                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
2179                                         foundone= 1;
2180                                         break;
2181                                 }
2182                         }
2183                         if(foundone) break;
2184                 }
2185
2186                 if(foundone) {
2187                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
2188
2189                         while(a--) {
2190                                 for(id= lbarray[a]->first; id; id= id->next) {
2191                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
2192                                                 writestruct(wd, ID_ID, "ID", 1, id);
2193                                         }
2194                                 }
2195                         }
2196                 }
2197         }
2198 }
2199
2200 static void write_bone(WriteData *wd, Bone* bone)
2201 {
2202         Bone*   cbone;
2203
2204         // PATCH for upward compatibility after 2.37+ armature recode
2205         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
2206                 
2207         // Write this bone
2208         writestruct(wd, DATA, "Bone", 1, bone);
2209
2210         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
2211          of library blocks that implement this.*/
2212         if (bone->prop)
2213                 IDP_WriteProperty(bone->prop, wd);
2214         
2215         // Write Children
2216         cbone= bone->childbase.first;
2217         while(cbone) {
2218                 write_bone(wd, cbone);
2219                 cbone= cbone->next;
2220         }
2221 }
2222
2223 static void write_armatures(WriteData *wd, ListBase *idbase)
2224 {
2225         bArmature       *arm;
2226         Bone            *bone;
2227
2228         arm=idbase->first;
2229         while (arm) {
2230                 if (arm->id.us>0 || wd->current) {
2231                         writestruct(wd, ID_AR, "bArmature", 1, arm);
2232                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
2233
2234                         if (arm->adt) write_animdata(wd, arm->adt);
2235
2236                         /* Direct data */
2237                         bone= arm->bonebase.first;
2238                         while(bone) {
2239                                 write_bone(wd, bone);
2240                                 bone=bone->next;
2241                         }
2242                 }
2243                 arm=arm->id.next;
2244         }
2245
2246         /* flush helps the compression for undo-save */
2247         mywrite(wd, MYWRITE_FLUSH, 0);
2248 }
2249
2250 static void write_texts(WriteData *wd, ListBase *idbase)
2251 {
2252         Text *text;
2253         TextLine *tmp;
2254         TextMarker *mrk;
2255
2256         text= idbase->first;
2257         while(text) {
2258                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
2259
2260                 /* write LibData */
2261                 writestruct(wd, ID_TXT, "Text", 1, text);
2262                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
2263                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
2264
2265                 if(!(text->flags & TXT_ISEXT)) {
2266                         /* now write the text data, in two steps for optimization in the readfunction */
2267                         tmp= text->lines.first;
2268                         while (tmp) {
2269                                 writestruct(wd, DATA, "TextLine", 1, tmp);
2270                                 tmp= tmp->next;
2271                         }
2272
2273                         tmp= text->lines.first;
2274                         while (tmp) {
2275                                 writedata(wd, DATA, tmp->len+1, tmp->line);
2276                                 tmp= tmp->next;
2277                         }
2278
2279                         /* write markers */
2280                         mrk= text->markers.first;
2281                         while (mrk) {
2282                                 writestruct(wd, DATA, "TextMarker", 1, mrk);
2283                                 mrk= mrk->next;
2284                         }
2285                 }
2286
2287
2288                 text= text->id.next;
2289         }
2290
2291         /* flush helps the compression for undo-save */
2292         mywrite(wd, MYWRITE_FLUSH, 0);
2293 }
2294
2295 static void write_sounds(WriteData *wd, ListBase *idbase)
2296 {
2297         bSound *sound;
2298
2299         PackedFile * pf;
2300
2301         sound= idbase->first;
2302         while(sound) {
2303                 if(sound->id.us>0 || wd->current) {
2304                         /* write LibData */
2305                         writestruct(wd, ID_SO, "bSound", 1, sound);
2306                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
2307
2308                         if (sound->packedfile) {
2309                                 pf = sound->packedfile;
2310                                 writestruct(wd, DATA, "PackedFile", 1, pf);
2311                                 writedata(wd, DATA, pf->size, pf->data);
2312                         }
2313                 }
2314                 sound= sound->id.next;
2315         }
2316
2317         /* flush helps the compression for undo-save */
2318         mywrite(wd, MYWRITE_FLUSH, 0);
2319 }
2320
2321 static void write_groups(WriteData *wd, ListBase *idbase)
2322 {
2323         Group *group;
2324         GroupObject *go;
2325
2326         for(group= idbase->first; group; group= group->id.next) {
2327                 if(group->id.us>0 || wd->current) {
2328                         /* write LibData */
2329                         writestruct(wd, ID_GR, "Group", 1, group);
2330                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
2331
2332                         go= group->gobject.first;
2333                         while(go) {
2334                                 writestruct(wd, DATA, "GroupObject", 1, go);
2335                                 go= go->next;
2336                         }
2337                 }
2338         }
2339 }
2340
2341 static void write_nodetrees(WriteData *wd, ListBase *idbase)
2342 {
2343         bNodeTree *ntree;
2344         
2345         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
2346                 if (ntree->id.us>0 || wd->current) {
2347                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
2348                         write_nodetree(wd, ntree);
2349                         
2350                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
2351                         
2352                         if (ntree->adt) write_animdata(wd, ntree->adt);
2353                 }
2354         }
2355 }
2356
2357 static void write_brushes(WriteData *wd, ListBase *idbase)
2358 {
2359         Brush *brush;
2360         
2361         for(brush=idbase->first; brush; brush= brush->id.next) {
2362                 if(brush->id.us>0 || wd->current) {
2363                         writestruct(wd, ID_BR, "Brush", 1, brush);
2364                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
2365                         
2366                         writestruct(wd, DATA, "MTex", 1, &brush->mtex);
2367                         
2368                         if(brush->curve)
2369                                 write_curvemapping(wd, brush->curve);
2370                 }
2371         }
2372 }
2373
2374 static void write_scripts(WriteData *wd, ListBase *idbase)
2375 {
2376         Script *script;
2377         
2378         for(script=idbase->first; script; script= script->id.next) {
2379                 if(script->id.us>0 || wd->current) {
2380                         writestruct(wd, ID_SCRIPT, "Script", 1, script);
2381                         if (script->id.properties) IDP_WriteProperty(script->id.properties, wd);
2382                 }
2383         }
2384 }
2385
2386 /* context is usually defined by WM, two cases where no WM is available:
2387  * - for forward compatibility, curscreen has to be saved
2388  * - for undofile, curscene needs to be saved */
2389 static void write_global(WriteData *wd, int fileflags, Main *mainvar)
2390 {
2391         FileGlobal fg;
2392         bScreen *screen;
2393         char subvstr[8];
2394         
2395         /* prevent mem checkers from complaining */
2396         fg.pads= fg.pad= 0;
2397         memset(fg.filename, 0, sizeof(fg.filename));
2398
2399         current_screen_compat(mainvar, &screen);
2400
2401         /* XXX still remap G */
2402         fg.curscreen= screen;
2403         fg.curscene= screen->scene;
2404         fg.displaymode= G.displaymode;
2405         fg.winpos= G.winpos;
2406         fg.fileflags= (fileflags & ~(G_FILE_NO_UI|G_FILE_RELATIVE_REMAP));      // prevent to save this, is not good convention, and feature with concerns...
2407         fg.globalf= G.f;
2408         BLI_strncpy(fg.filename, mainvar->name, sizeof(fg.filename));
2409
2410         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
2411         memcpy(fg.subvstr, subvstr, 4);
2412         
2413         fg.subversion= BLENDER_SUBVERSION;
2414         fg.minversion= BLENDER_MINVERSION;
2415         fg.minsubversion= BLENDER_MINSUBVERSION;
2416 #ifdef NAN_BUILDINFO
2417         {
2418                 extern char build_rev[];
2419                 fg.revision= atoi(build_rev);
2420         }
2421 #else
2422         fg.revision= 0;
2423 #endif
2424         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
2425 }
2426
2427 /* preview image, first 2 values are width and height
2428  * second are an RGBA image (unsigned char)
2429  * note, this uses 'TEST' since new types will segfault on file load for older blender versions.
2430  */
2431 static void write_thumb(WriteData *wd, int *img)
2432 {
2433         if(img)
2434                 writedata(wd, TEST, (2 + img[0] * img[1]) * sizeof(int), img);
2435 }
2436
2437 /* if MemFile * there's filesave to memory */
2438 static int write_file_handle(Main *mainvar, int handle, MemFile *compare, MemFile *current, 
2439                                                          int write_user_block, int write_flags, int *thumb)
2440 {
2441         BHead bhead;
2442         ListBase mainlist;
2443         char buf[16];
2444         WriteData *wd;
2445
2446         blo_split_main(&mainlist, mainvar);
2447
2448         wd= bgnwrite(handle, compare, current);
2449         
2450         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (ENDIAN_ORDER==B_ENDIAN)?'V':'v', BLENDER_VERSION);
2451         mywrite(wd, buf, 12);
2452
2453         write_renderinfo(wd, mainvar);
2454         write_thumb(wd, thumb);
2455         write_global(wd, write_flags, mainvar);
2456
2457         /* no UI save in undo */
2458         if(current==NULL) {
2459                 write_windowmanagers(wd, &mainvar->wm);
2460                 write_screens  (wd, &mainvar->screen);
2461         }
2462         write_scenes   (wd, &mainvar->scene);
2463         write_curves   (wd, &mainvar->curve);
2464         write_mballs   (wd, &mainvar->mball);
2465         write_images   (wd, &mainvar->image);
2466         write_cameras  (wd, &mainvar->camera);
2467         write_lamps    (wd, &mainvar->lamp);
2468         write_lattices (wd, &mainvar->latt);
2469         write_vfonts   (wd, &mainvar->vfont);
2470         write_keys     (wd, &mainvar->key);
2471         write_worlds   (wd, &mainvar->world);
2472         write_texts    (wd, &mainvar->text);
2473         write_sounds   (wd, &mainvar->sound);
2474         write_groups   (wd, &mainvar->group);
2475         write_armatures(wd, &mainvar->armature);
2476         write_actions  (wd, &mainvar->action);
2477         write_objects  (wd, &mainvar->object);
2478         write_materials(wd, &mainvar->mat);
2479         write_textures (wd, &mainvar->tex);
2480         write_meshs    (wd, &mainvar->mesh);
2481         write_particlesettings(wd, &mainvar->particle);
2482         write_nodetrees(wd, &mainvar->nodetree);
2483         write_brushes  (wd, &mainvar->brush);
2484         write_scripts  (wd, &mainvar->script);
2485         write_gpencils (wd, &mainvar->gpencil);
2486         write_libraries(wd,  mainvar->next);
2487
2488         if (write_user_block) {
2489                 write_userdef(wd);
2490         }
2491                                                         
2492         /* dna as last, because (to be implemented) test for which structs are written */
2493         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
2494
2495         /* end of file */
2496         memset(&bhead, 0, sizeof(BHead));
2497         bhead.code= ENDB;
2498         mywrite(wd, &bhead, sizeof(BHead));
2499
2500         blo_join_main(&mainlist);
2501
2502         return endwrite(wd);
2503 }
2504
2505 /* return: success (1) */
2506 int BLO_write_file(Main *mainvar, char *dir, int write_flags, ReportList *reports, int *thumb)
2507 {
2508         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
2509         char tempname[FILE_MAXDIR+FILE_MAXFILE+1];
2510         int file, err, write_user_block;
2511
2512         /* open temporary file, so we preserve the original in case we crash */
2513         BLI_snprintf(tempname, sizeof(tempname), "%s@", dir);
2514
2515         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
2516         if(file == -1) {
2517                 BKE_reportf(reports, RPT_ERROR, "Can't open file %s for writing: %s.", tempname, strerror(errno));
2518                 return 0;
2519         }
2520
2521         /* remapping of relative paths to new file location */
2522         if(write_flags & G_FILE_RELATIVE_REMAP) {
2523                 char dir1[FILE_MAXDIR+FILE_MAXFILE];
2524                 char dir2[FILE_MAXDIR+FILE_MAXFILE];
2525                 BLI_split_dirfile(dir, dir1, NULL);
2526                 BLI_split_dirfile(mainvar->name, dir2, NULL);
2527
2528                 /* just incase there is some subtle difference */
2529                 BLI_cleanup_dir(mainvar->name, dir1);
2530                 BLI_cleanup_dir(mainvar->name, dir2);
2531
2532                 if(strcmp(dir1, dir2)==0)
2533                         write_flags &= ~G_FILE_RELATIVE_REMAP;
2534                 else
2535                         makeFilesAbsolute(mainvar, G.main->name, NULL);
2536         }
2537
2538         BLI_make_file_string(G.main->name, userfilename, BLI_get_folder_create(BLENDER_USER_CONFIG, NULL), BLENDER_STARTUP_FILE);
2539         write_user_block= BLI_streq(dir, userfilename);
2540
2541         if(write_flags & G_FILE_RELATIVE_REMAP)
2542                 makeFilesRelative(mainvar, dir, NULL); /* note, making relative to something OTHER then G.main->name */
2543
2544         /* actual file writing */
2545         err= write_file_handle(mainvar, file, NULL,NULL, write_user_block, write_flags, thumb);
2546         close(file);
2547
2548         /* rename/compress */
2549         if(!err) {
2550                 if(write_flags & G_FILE_COMPRESS) {
2551                         /* compressed files have the same ending as regular files... only from 2.4!!! */
2552                         char gzname[FILE_MAXDIR+FILE_MAXFILE+4];
2553                         int ret;
2554
2555                         /* first write compressed to separate @.gz */
2556                         BLI_snprintf(gzname, sizeof(gzname), "%s@.gz", dir);
2557                         ret = BLI_gzip(tempname, gzname);
2558                         
2559                         if(0==ret) {
2560                                 /* now rename to real file name, and delete temp @ file too */
2561                                 if(BLI_rename(gzname, dir) != 0) {
2562                                         BKE_report(reports, RPT_ERROR, "Can't change old file. File saved with @.");
2563                                         return 0;
2564                                 }
2565
2566                                 BLI_delete(tempname, 0, 0);
2567                         }
2568                         else if(-1==ret) {
2569                                 BKE_report(reports, RPT_ERROR, "Failed opening .gz file.");
2570                                 return 0;
2571                         }
2572                         else if(-2==ret) {
2573                                 BKE_report(reports, RPT_ERROR, "Failed opening .blend file for compression.");
2574                                 return 0;
2575                         }
2576                 }
2577                 else if(BLI_rename(tempname, dir) != 0) {
2578                         BKE_report(reports, RPT_ERROR, "Can't change old file. File saved with @");
2579                         return 0;
2580                 }
2581                 
2582         }
2583         else {
2584                 BKE_report(reports, RPT_ERROR, strerror(errno));
2585                 remove(tempname);
2586
2587                 return 0;
2588         }
2589
2590         return 1;
2591 }
2592
2593 /* return: success (1) */
2594 int BLO_write_file_mem(Main *mainvar, MemFile *compare, MemFile *current, int write_flags)
2595 {
2596         int err;
2597
2598         err= write_file_handle(mainvar, 0, compare, current, 0, write_flags, NULL);
2599         
2600         if(err==0) return 1;
2601         return 0;
2602 }
2603
2604
2605         /* Runtime writing */
2606
2607 static char *get_runtime_path(char *exename) {
2608         char *installpath= get_install_dir();
2609
2610         if (!installpath) {
2611                 return NULL;
2612         }
2613         else {
2614                 char *path= BLI_sprintfN("%s%c%s", installpath, SEP, exename);
2615
2616                 if (path == NULL) {
2617                         MEM_freeN(installpath);
2618                         return NULL;
2619                 }
2620
2621                 MEM_freeN(installpath);
2622
2623                 return path;
2624         }
2625 }
2626
2627 #ifdef __APPLE__
2628
2629 static int recursive_copy_runtime(const char *outname, char *exename, ReportList *reports)
2630 {
2631         char *runtime = get_runtime_path(exename);
2632         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
2633         int progfd = -1, error= 0;
2634
2635         if (!runtime) {
2636                 BKE_report(reports, RPT_ERROR, "Unable to find runtime");
2637                 error= 1;
2638                 goto cleanup;
2639         }
2640         //printf("runtimepath %s\n", runtime);
2641                 
2642         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2643         if (progfd==-1) {
2644                 BKE_report(reports, RPT_ERROR, "Unable to find runtime");
2645                 error= 1;
2646                 goto cleanup;
2647         }
2648
2649         sprintf(command, "/bin/cp -R \"%s\" \"%s\"", runtime, outname);
2650         //printf("command %s\n", command);
2651         if (system(command) == -1) {
2652                 BKE_report(reports, RPT_ERROR, "Couldn't copy runtime");
2653                 error= 1;
2654         }
2655
2656 cleanup:
2657         if (progfd!=-1)
2658                 close(progfd);
2659         if (runtime)
2660                 MEM_freeN(runtime);
2661
2662         return !error;
2663 }
2664
2665 int BLO_write_runtime(Main *mainvar, const char *file, char *exename, ReportList *reports) 
2666 {
2667         char gamename[FILE_MAXDIR+FILE_MAXFILE];
2668         int outfd = -1, error= 0;
2669
2670         // remove existing file / bundle
2671         //printf("Delete file %s\n", file);
2672         BLI_delete(file, 0, TRUE);
2673
2674         if (!recursive_copy_runtime(file, exename, reports)) {
2675                 error= 1;
2676                 goto cleanup;
2677         }
2678
2679         BLI_snprintf(gamename, sizeof(gamename), "%s/Contents/Resources/game.blend", file);
2680         //printf("gamename %s\n", gamename);
2681         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2682         if (outfd != -1) {
2683
2684                 write_file_handle(mainvar, outfd, NULL,NULL, 0, G.fileflags, NULL);
2685
2686                 if (write(outfd, " ", 1) != 1) {
2687                         BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2688                         error= 1;
2689                         goto cleanup;
2690                 }
2691         } else {
2692                 BKE_report(reports, RPT_ERROR, "Unable to open blenderfile.");
2693                 error= 1;
2694         }
2695
2696 cleanup:
2697         if (outfd!=-1)
2698                 close(outfd);
2699
2700         BKE_reports_prepend(reports, "Unable to make runtime: ");
2701         return !error;
2702 }
2703
2704 #else /* !__APPLE__ */
2705
2706 static int handle_append_runtime(int handle, char *exename, ReportList *reports)
2707 {
2708         char *runtime= get_runtime_path(exename);
2709         unsigned char buf[1024];
2710         int count, progfd= -1, error= 0;
2711
2712         if (!BLI_exists(runtime)) {
2713                 BKE_report(reports, RPT_ERROR, "Unable to find runtime.");
2714                 error= 1;
2715                 goto cleanup;
2716         }
2717
2718         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2719         if (progfd==-1) {
2720                 BKE_report(reports, RPT_ERROR, "Unable to find runtime.@");
2721                 error= 1;
2722                 goto cleanup;
2723         }
2724
2725         while ((count= read(progfd, buf, sizeof(buf)))>0) {
2726                 if (write(handle, buf, count)!=count) {
2727                         BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2728                         error= 1;
2729                         goto cleanup;
2730                 }
2731         }
2732
2733 cleanup:
2734         if (progfd!=-1)
2735                 close(progfd);
2736         if (runtime)
2737                 MEM_freeN(runtime);
2738
2739         return !error;
2740 }
2741
2742 static int handle_write_msb_int(int handle, int i) 
2743 {
2744         unsigned char buf[4];
2745         buf[0]= (i>>24)&0xFF;
2746         buf[1]= (i>>16)&0xFF;
2747         buf[2]= (i>>8)&0xFF;
2748         buf[3]= (i>>0)&0xFF;
2749
2750         return (write(handle, buf, 4)==4);
2751 }
2752
2753 int BLO_write_runtime(Main *mainvar, const char *file, char *exename, ReportList *reports)
2754 {
2755         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2756         int datastart, error= 0;
2757
2758         if (!outfd) {
2759                 BKE_report(reports, RPT_ERROR, "Unable to open output file.");
2760                 error= 1;
2761                 goto cleanup;
2762         }
2763         if (!handle_append_runtime(outfd, exename, reports)) {
2764                 error= 1;
2765                 goto cleanup;
2766         }
2767
2768         datastart= lseek(outfd, 0, SEEK_CUR);
2769
2770         write_file_handle(mainvar, outfd, NULL,NULL, 0, G.fileflags, NULL);
2771
2772         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
2773                 BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2774                 error= 1;
2775                 goto cleanup;
2776         }
2777
2778 cleanup:
2779         if (outfd!=-1)
2780                 close(outfd);
2781
2782         BKE_reports_prepend(reports, "Unable to make runtime: ");
2783         return !error;
2784 }
2785
2786 #endif /* !__APPLE__ */