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