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