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