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