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