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