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