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