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