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