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