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