Slightly generalized the crash fix in revision 54111.
[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                 if (bext->prop) {
859                         IDP_WriteProperty(bext->prop, wd);
860                 }
861         }
862         
863         for (style= U.uistyles.first; style; style= style->next) {
864                 writestruct(wd, DATA, "uiStyle", 1, style);
865         }
866 }
867
868 static void write_boid_state(WriteData *wd, BoidState *state)
869 {
870         BoidRule *rule = state->rules.first;
871         //BoidCondition *cond = state->conditions.first;
872
873         writestruct(wd, DATA, "BoidState", 1, state);
874
875         for (; rule; rule=rule->next) {
876                 switch (rule->type) {
877                         case eBoidRuleType_Goal:
878                         case eBoidRuleType_Avoid:
879                                 writestruct(wd, DATA, "BoidRuleGoalAvoid", 1, rule);
880                                 break;
881                         case eBoidRuleType_AvoidCollision:
882                                 writestruct(wd, DATA, "BoidRuleAvoidCollision", 1, rule);
883                                 break;
884                         case eBoidRuleType_FollowLeader:
885                                 writestruct(wd, DATA, "BoidRuleFollowLeader", 1, rule);
886                                 break;
887                         case eBoidRuleType_AverageSpeed:
888                                 writestruct(wd, DATA, "BoidRuleAverageSpeed", 1, rule);
889                                 break;
890                         case eBoidRuleType_Fight:
891                                 writestruct(wd, DATA, "BoidRuleFight", 1, rule);
892                                 break;
893                         default:
894                                 writestruct(wd, DATA, "BoidRule", 1, rule);
895                                 break;
896                 }
897         }
898         //for (; cond; cond=cond->next)
899         //      writestruct(wd, DATA, "BoidCondition", 1, cond);
900 }
901
902 /* update this also to readfile.c */
903 static const char *ptcache_data_struct[] = {
904         "", // BPHYS_DATA_INDEX
905         "", // BPHYS_DATA_LOCATION
906         "", // BPHYS_DATA_VELOCITY
907         "", // BPHYS_DATA_ROTATION
908         "", // BPHYS_DATA_AVELOCITY / BPHYS_DATA_XCONST */
909         "", // BPHYS_DATA_SIZE:
910         "", // BPHYS_DATA_TIMES:
911         "BoidData" // case BPHYS_DATA_BOIDS:
912 };
913 static const char *ptcache_extra_struct[] = {
914         "",
915         "ParticleSpring"
916 };
917 static void write_pointcaches(WriteData *wd, ListBase *ptcaches)
918 {
919         PointCache *cache = ptcaches->first;
920         int i;
921
922         for (; cache; cache=cache->next) {
923                 writestruct(wd, DATA, "PointCache", 1, cache);
924
925                 if ((cache->flag & PTCACHE_DISK_CACHE)==0) {
926                         PTCacheMem *pm = cache->mem_cache.first;
927
928                         for (; pm; pm=pm->next) {
929                                 PTCacheExtra *extra = pm->extradata.first;
930
931                                 writestruct(wd, DATA, "PTCacheMem", 1, pm);
932                                 
933                                 for (i=0; i<BPHYS_TOT_DATA; i++) {
934                                         if (pm->data[i] && pm->data_types & (1<<i)) {
935                                                 if (ptcache_data_struct[i][0]=='\0')
936                                                         writedata(wd, DATA, MEM_allocN_len(pm->data[i]), pm->data[i]);
937                                                 else
938                                                         writestruct(wd, DATA, ptcache_data_struct[i], pm->totpoint, pm->data[i]);
939                                         }
940                                 }
941
942                                 for (; extra; extra=extra->next) {
943                                         if (ptcache_extra_struct[extra->type][0]=='\0')
944                                                 continue;
945                                         writestruct(wd, DATA, "PTCacheExtra", 1, extra);
946                                         writestruct(wd, DATA, ptcache_extra_struct[extra->type], extra->totdata, extra->data);
947                                 }
948                         }
949                 }
950         }
951 }
952 static void write_particlesettings(WriteData *wd, ListBase *idbase)
953 {
954         ParticleSettings *part;
955         ParticleDupliWeight *dw;
956         GroupObject *go;
957         int a;
958
959         part= idbase->first;
960         while (part) {
961                 if (part->id.us>0 || wd->current) {
962                         /* write LibData */
963                         writestruct(wd, ID_PA, "ParticleSettings", 1, part);
964                         if (part->id.properties) IDP_WriteProperty(part->id.properties, wd);
965                         if (part->adt) write_animdata(wd, part->adt);
966                         writestruct(wd, DATA, "PartDeflect", 1, part->pd);
967                         writestruct(wd, DATA, "PartDeflect", 1, part->pd2);
968                         writestruct(wd, DATA, "EffectorWeights", 1, part->effector_weights);
969
970                         dw = part->dupliweights.first;
971                         for (; dw; dw=dw->next) {
972                                 /* update indices */
973                                 dw->index = 0;
974                                 if (part->dup_group) { /* can be NULL if lining fails or set to None */
975                                         go = part->dup_group->gobject.first;
976                                         while (go && go->ob != dw->ob) {
977                                                 go=go->next;
978                                                 dw->index++;
979                                         }
980                                 }
981                                 writestruct(wd, DATA, "ParticleDupliWeight", 1, dw);
982                         }
983
984                         if (part->boids && part->phystype == PART_PHYS_BOIDS) {
985                                 BoidState *state = part->boids->states.first;
986
987                                 writestruct(wd, DATA, "BoidSettings", 1, part->boids);
988
989                                 for (; state; state=state->next)
990                                         write_boid_state(wd, state);
991                         }
992                         if (part->fluid && part->phystype == PART_PHYS_FLUID) {
993                                 writestruct(wd, DATA, "SPHFluidSettings", 1, part->fluid); 
994                         }
995
996                         for (a=0; a<MAX_MTEX; a++) {
997                                 if (part->mtex[a]) writestruct(wd, DATA, "MTex", 1, part->mtex[a]);
998                         }
999                 }
1000                 part= part->id.next;
1001         }
1002 }
1003 static void write_particlesystems(WriteData *wd, ListBase *particles)
1004 {
1005         ParticleSystem *psys= particles->first;
1006         ParticleTarget *pt;
1007         int a;
1008
1009         for (; psys; psys=psys->next) {
1010                 writestruct(wd, DATA, "ParticleSystem", 1, psys);
1011
1012                 if (psys->particles) {
1013                         writestruct(wd, DATA, "ParticleData", psys->totpart, psys->particles);
1014
1015                         if (psys->particles->hair) {
1016                                 ParticleData *pa = psys->particles;
1017
1018                                 for (a=0; a<psys->totpart; a++, pa++)
1019                                         writestruct(wd, DATA, "HairKey", pa->totkey, pa->hair);
1020                         }
1021
1022                         if (psys->particles->boid && psys->part->phystype == PART_PHYS_BOIDS)
1023                                 writestruct(wd, DATA, "BoidParticle", psys->totpart, psys->particles->boid);
1024
1025                         if (psys->part->fluid && psys->part->phystype == PART_PHYS_FLUID && (psys->part->fluid->flag & SPH_VISCOELASTIC_SPRINGS))
1026                                 writestruct(wd, DATA, "ParticleSpring", psys->tot_fluidsprings, psys->fluid_springs);
1027                 }
1028                 pt = psys->targets.first;
1029                 for (; pt; pt=pt->next)
1030                         writestruct(wd, DATA, "ParticleTarget", 1, pt);
1031
1032                 if (psys->child) writestruct(wd, DATA, "ChildParticle", psys->totchild, psys->child);
1033
1034                 if (psys->clmd) {
1035                         writestruct(wd, DATA, "ClothModifierData", 1, psys->clmd);
1036                         writestruct(wd, DATA, "ClothSimSettings", 1, psys->clmd->sim_parms);
1037                         writestruct(wd, DATA, "ClothCollSettings", 1, psys->clmd->coll_parms);
1038                 }
1039
1040                 write_pointcaches(wd, &psys->ptcaches);
1041         }
1042 }
1043
1044 static void write_properties(WriteData *wd, ListBase *lb)
1045 {
1046         bProperty *prop;
1047
1048         prop= lb->first;
1049         while (prop) {
1050                 writestruct(wd, DATA, "bProperty", 1, prop);
1051
1052                 if (prop->poin && prop->poin != &prop->data)
1053                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
1054
1055                 prop= prop->next;
1056         }
1057 }
1058
1059 static void write_sensors(WriteData *wd, ListBase *lb)
1060 {
1061         bSensor *sens;
1062
1063         sens= lb->first;
1064         while (sens) {
1065                 writestruct(wd, DATA, "bSensor", 1, sens);
1066
1067                 writedata(wd, DATA, sizeof(void *)*sens->totlinks, sens->links);
1068
1069                 switch (sens->type) {
1070                 case SENS_NEAR:
1071                         writestruct(wd, DATA, "bNearSensor", 1, sens->data);
1072                         break;
1073                 case SENS_MOUSE:
1074                         writestruct(wd, DATA, "bMouseSensor", 1, sens->data);
1075                         break;
1076                 case SENS_TOUCH:
1077                         writestruct(wd, DATA, "bTouchSensor", 1, sens->data);
1078                         break;
1079                 case SENS_KEYBOARD:
1080                         writestruct(wd, DATA, "bKeyboardSensor", 1, sens->data);
1081                         break;
1082                 case SENS_PROPERTY:
1083                         writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
1084                         break;
1085                 case SENS_ARMATURE:
1086                         writestruct(wd, DATA, "bArmatureSensor", 1, sens->data);
1087                         break;
1088                 case SENS_ACTUATOR:
1089                         writestruct(wd, DATA, "bActuatorSensor", 1, sens->data);
1090                         break;
1091                 case SENS_DELAY:
1092                         writestruct(wd, DATA, "bDelaySensor", 1, sens->data);
1093                         break;
1094                 case SENS_COLLISION:
1095                         writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
1096                         break;
1097                 case SENS_RADAR:
1098                         writestruct(wd, DATA, "bRadarSensor", 1, sens->data);
1099                         break;
1100                 case SENS_RANDOM:
1101                         writestruct(wd, DATA, "bRandomSensor", 1, sens->data);
1102                         break;
1103                 case SENS_RAY:
1104                         writestruct(wd, DATA, "bRaySensor", 1, sens->data);
1105                         break;
1106                 case SENS_MESSAGE:
1107                         writestruct(wd, DATA, "bMessageSensor", 1, sens->data);
1108                         break;
1109                 case SENS_JOYSTICK:
1110                         writestruct(wd, DATA, "bJoystickSensor", 1, sens->data);
1111                         break;
1112                 default:
1113                         ; /* error: don't know how to write this file */
1114                 }
1115
1116                 sens= sens->next;
1117         }
1118 }
1119
1120 static void write_controllers(WriteData *wd, ListBase *lb)
1121 {
1122         bController *cont;
1123
1124         cont= lb->first;
1125         while (cont) {
1126                 writestruct(wd, DATA, "bController", 1, cont);
1127
1128                 writedata(wd, DATA, sizeof(void *)*cont->totlinks, cont->links);
1129
1130                 switch (cont->type) {
1131                 case CONT_EXPRESSION:
1132                         writestruct(wd, DATA, "bExpressionCont", 1, cont->data);
1133                         break;
1134                 case CONT_PYTHON:
1135                         writestruct(wd, DATA, "bPythonCont", 1, cont->data);
1136                         break;
1137                 default:
1138                         ; /* error: don't know how to write this file */
1139                 }
1140
1141                 cont= cont->next;
1142         }
1143 }
1144
1145 static void write_actuators(WriteData *wd, ListBase *lb)
1146 {
1147         bActuator *act;
1148
1149         act= lb->first;
1150         while (act) {
1151                 writestruct(wd, DATA, "bActuator", 1, act);
1152
1153                 switch (act->type) {
1154                 case ACT_ACTION:
1155                 case ACT_SHAPEACTION:
1156                         writestruct(wd, DATA, "bActionActuator", 1, act->data);
1157                         break;
1158                 case ACT_SOUND:
1159                         writestruct(wd, DATA, "bSoundActuator", 1, act->data);
1160                         break;
1161                 case ACT_OBJECT:
1162                         writestruct(wd, DATA, "bObjectActuator", 1, act->data);
1163                         break;
1164                 case ACT_IPO:
1165                         writestruct(wd, DATA, "bIpoActuator", 1, act->data);
1166                         break;
1167                 case ACT_PROPERTY:
1168                         writestruct(wd, DATA, "bPropertyActuator", 1, act->data);
1169                         break;
1170                 case ACT_CAMERA:
1171                         writestruct(wd, DATA, "bCameraActuator", 1, act->data);
1172                         break;
1173                 case ACT_CONSTRAINT:
1174                         writestruct(wd, DATA, "bConstraintActuator", 1, act->data);
1175                         break;
1176                 case ACT_EDIT_OBJECT:
1177                         writestruct(wd, DATA, "bEditObjectActuator", 1, act->data);
1178                         break;
1179                 case ACT_SCENE:
1180                         writestruct(wd, DATA, "bSceneActuator", 1, act->data);
1181                         break;
1182                 case ACT_GROUP:
1183                         writestruct(wd, DATA, "bGroupActuator", 1, act->data);
1184                         break;
1185                 case ACT_RANDOM:
1186                         writestruct(wd, DATA, "bRandomActuator", 1, act->data);
1187                         break;
1188                 case ACT_MESSAGE:
1189                         writestruct(wd, DATA, "bMessageActuator", 1, act->data);
1190                         break;
1191                 case ACT_GAME:
1192                         writestruct(wd, DATA, "bGameActuator", 1, act->data);
1193                         break;
1194                 case ACT_VISIBILITY:
1195                         writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
1196                         break;
1197                 case ACT_2DFILTER:
1198                         writestruct(wd, DATA, "bTwoDFilterActuator", 1, act->data);
1199                         break;
1200                 case ACT_PARENT:
1201                         writestruct(wd, DATA, "bParentActuator", 1, act->data);
1202                         break;
1203                 case ACT_STATE:
1204                         writestruct(wd, DATA, "bStateActuator", 1, act->data);
1205                         break;
1206                 case ACT_ARMATURE:
1207                         writestruct(wd, DATA, "bArmatureActuator", 1, act->data);
1208                         break;
1209                 case ACT_STEERING:
1210                         writestruct(wd, DATA, "bSteeringActuator", 1, act->data);
1211                         break;
1212                 default:
1213                         ; /* error: don't know how to write this file */
1214                 }
1215
1216                 act= act->next;
1217         }
1218 }
1219
1220 static void write_motionpath(WriteData *wd, bMotionPath *mpath)
1221 {
1222         /* sanity checks */
1223         if (mpath == NULL)
1224                 return;
1225         
1226         /* firstly, just write the motionpath struct */
1227         writestruct(wd, DATA, "bMotionPath", 1, mpath);
1228         
1229         /* now write the array of data */
1230         writestruct(wd, DATA, "bMotionPathVert", mpath->length, mpath->points);
1231 }
1232
1233 static void write_constraints(WriteData *wd, ListBase *conlist)
1234 {
1235         bConstraint *con;
1236
1237         for (con=conlist->first; con; con=con->next) {
1238                 bConstraintTypeInfo *cti= BKE_constraint_get_typeinfo(con);
1239                 
1240                 /* Write the specific data */
1241                 if (cti && con->data) {
1242                         /* firstly, just write the plain con->data struct */
1243                         writestruct(wd, DATA, cti->structName, 1, con->data);
1244                         
1245                         /* do any constraint specific stuff */
1246                         switch (con->type) {
1247                                 case CONSTRAINT_TYPE_PYTHON:
1248                                 {
1249                                         bPythonConstraint *data = (bPythonConstraint *)con->data;
1250                                         bConstraintTarget *ct;
1251                                         
1252                                         /* write targets */
1253                                         for (ct= data->targets.first; ct; ct= ct->next)
1254                                                 writestruct(wd, DATA, "bConstraintTarget", 1, ct);
1255                                         
1256                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1257                                          * of library blocks that implement this.*/
1258                                         IDP_WriteProperty(data->prop, wd);
1259                                 }
1260                                         break;
1261                                 case CONSTRAINT_TYPE_SPLINEIK: 
1262                                 {
1263                                         bSplineIKConstraint *data = (bSplineIKConstraint *)con->data;
1264                                         
1265                                         /* write points array */
1266                                         writedata(wd, DATA, sizeof(float)*(data->numpoints), data->points);
1267                                 }
1268                                         break;
1269                         }
1270                 }
1271                 
1272                 /* Write the constraint */
1273                 writestruct(wd, DATA, "bConstraint", 1, con);
1274         }
1275 }
1276
1277 static void write_pose(WriteData *wd, bPose *pose)
1278 {
1279         bPoseChannel *chan;
1280         bActionGroup *grp;
1281
1282         /* Write each channel */
1283         if (!pose)
1284                 return;
1285
1286         /* Write channels */
1287         for (chan=pose->chanbase.first; chan; chan=chan->next) {
1288                 /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1289                  * of library blocks that implement this.*/
1290                 if (chan->prop)
1291                         IDP_WriteProperty(chan->prop, wd);
1292                 
1293                 write_constraints(wd, &chan->constraints);
1294                 
1295                 write_motionpath(wd, chan->mpath);
1296                 
1297                 /* prevent crashes with autosave, when a bone duplicated in editmode has not yet been assigned to its posechannel */
1298                 if (chan->bone) 
1299                         chan->selectflag= chan->bone->flag & BONE_SELECTED; /* gets restored on read, for library armatures */
1300                 
1301                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
1302         }
1303         
1304         /* Write groups */
1305         for (grp=pose->agroups.first; grp; grp=grp->next) 
1306                 writestruct(wd, DATA, "bActionGroup", 1, grp);
1307
1308         /* write IK param */
1309         if (pose->ikparam) {
1310                 char *structname = (char *)BKE_pose_ikparam_get_name(pose);
1311                 if (structname)
1312                         writestruct(wd, DATA, structname, 1, pose->ikparam);
1313         }
1314
1315         /* Write this pose */
1316         writestruct(wd, DATA, "bPose", 1, pose);
1317
1318 }
1319
1320 static void write_defgroups(WriteData *wd, ListBase *defbase)
1321 {
1322         bDeformGroup    *defgroup;
1323
1324         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
1325                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
1326 }
1327
1328 static void write_modifiers(WriteData *wd, ListBase *modbase)
1329 {
1330         ModifierData *md;
1331
1332         if (modbase == NULL) return;
1333         for (md=modbase->first; md; md= md->next) {
1334                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1335                 if (mti == NULL) return;
1336                 
1337                 writestruct(wd, DATA, mti->structName, 1, md);
1338                         
1339                 if (md->type==eModifierType_Hook) {
1340                         HookModifierData *hmd = (HookModifierData*) md;
1341                         
1342                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
1343                 }
1344                 else if (md->type==eModifierType_Cloth) {
1345                         ClothModifierData *clmd = (ClothModifierData*) md;
1346                         
1347                         writestruct(wd, DATA, "ClothSimSettings", 1, clmd->sim_parms);
1348                         writestruct(wd, DATA, "ClothCollSettings", 1, clmd->coll_parms);
1349                         writestruct(wd, DATA, "EffectorWeights", 1, clmd->sim_parms->effector_weights);
1350                         write_pointcaches(wd, &clmd->ptcaches);
1351                 }
1352                 else if (md->type==eModifierType_Smoke) {
1353                         SmokeModifierData *smd = (SmokeModifierData*) md;
1354                         
1355                         if (smd->type & MOD_SMOKE_TYPE_DOMAIN) {
1356                                 if (smd->domain) {
1357                                         write_pointcaches(wd, &(smd->domain->ptcaches[0]));
1358
1359                                         /* create fake pointcache so that old blender versions can read it */
1360                                         smd->domain->point_cache[1] = BKE_ptcache_add(&smd->domain->ptcaches[1]);
1361                                         smd->domain->point_cache[1]->flag |= PTCACHE_DISK_CACHE|PTCACHE_FAKE_SMOKE;
1362                                         smd->domain->point_cache[1]->step = 1;
1363
1364                                         write_pointcaches(wd, &(smd->domain->ptcaches[1]));
1365                                 }
1366                                 
1367                                 writestruct(wd, DATA, "SmokeDomainSettings", 1, smd->domain);
1368
1369                                 if (smd->domain) {
1370                                         /* cleanup the fake pointcache */
1371                                         BKE_ptcache_free_list(&smd->domain->ptcaches[1]);
1372                                         smd->domain->point_cache[1] = NULL;
1373                                         
1374                                         writestruct(wd, DATA, "EffectorWeights", 1, smd->domain->effector_weights);
1375                                 }
1376                         }
1377                         else if (smd->type & MOD_SMOKE_TYPE_FLOW)
1378                                 writestruct(wd, DATA, "SmokeFlowSettings", 1, smd->flow);
1379                         else if (smd->type & MOD_SMOKE_TYPE_COLL)
1380                                 writestruct(wd, DATA, "SmokeCollSettings", 1, smd->coll);
1381                 }
1382                 else if (md->type==eModifierType_Fluidsim) {
1383                         FluidsimModifierData *fluidmd = (FluidsimModifierData*) md;
1384                         
1385                         writestruct(wd, DATA, "FluidsimSettings", 1, fluidmd->fss);
1386                 }
1387                 else if (md->type==eModifierType_DynamicPaint) {
1388                         DynamicPaintModifierData *pmd = (DynamicPaintModifierData*) md;
1389                         
1390                         if (pmd->canvas) {
1391                                 DynamicPaintSurface *surface;
1392                                 writestruct(wd, DATA, "DynamicPaintCanvasSettings", 1, pmd->canvas);
1393                                 
1394                                 /* write surfaces */
1395                                 for (surface=pmd->canvas->surfaces.first; surface; surface=surface->next)
1396                                         writestruct(wd, DATA, "DynamicPaintSurface", 1, surface);
1397                                 /* write caches and effector weights */
1398                                 for (surface=pmd->canvas->surfaces.first; surface; surface=surface->next) {
1399                                         write_pointcaches(wd, &(surface->ptcaches));
1400
1401                                         writestruct(wd, DATA, "EffectorWeights", 1, surface->effector_weights);
1402                                 }
1403                         }
1404                         if (pmd->brush) {
1405                                 writestruct(wd, DATA, "DynamicPaintBrushSettings", 1, pmd->brush);
1406                                 writestruct(wd, DATA, "ColorBand", 1, pmd->brush->paint_ramp);
1407                                 writestruct(wd, DATA, "ColorBand", 1, pmd->brush->vel_ramp);
1408                         }
1409                 }
1410                 else if (md->type==eModifierType_Collision) {
1411                         
1412 #if 0
1413                         CollisionModifierData *collmd = (CollisionModifierData*) md;
1414                         // TODO: CollisionModifier should use pointcache 
1415                         // + have proper reset events before enabling this
1416                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->x);
1417                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->xnew);
1418                         writestruct(wd, DATA, "MFace", collmd->numfaces, collmd->mfaces);
1419 #endif
1420                 }
1421                 else if (md->type==eModifierType_MeshDeform) {
1422                         MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
1423                         int size = mmd->dyngridsize;
1424
1425                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->bindinfluences);
1426                         writedata(wd, DATA, sizeof(int) * (mmd->totvert + 1), mmd->bindoffsets);
1427                         writedata(wd, DATA, sizeof(float) * 3 * mmd->totcagevert,
1428                                 mmd->bindcagecos);
1429                         writestruct(wd, DATA, "MDefCell", size*size*size, mmd->dyngrid);
1430                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->dyninfluences);
1431                         writedata(wd, DATA, sizeof(int)*mmd->totvert, mmd->dynverts);
1432                 }
1433                 else if (md->type==eModifierType_Warp) {
1434                         WarpModifierData *tmd = (WarpModifierData*) md;
1435                         if (tmd->curfalloff) {
1436                                 write_curvemapping(wd, tmd->curfalloff);
1437                         }
1438                 }
1439                 else if (md->type==eModifierType_WeightVGEdit) {
1440                         WeightVGEditModifierData *wmd = (WeightVGEditModifierData*) md;
1441
1442                         if (wmd->cmap_curve)
1443                                 write_curvemapping(wd, wmd->cmap_curve);
1444                 }
1445         }
1446 }
1447
1448 static void write_objects(WriteData *wd, ListBase *idbase)
1449 {
1450         Object *ob;
1451         
1452         ob= idbase->first;
1453         while (ob) {
1454                 if (ob->id.us>0 || wd->current) {
1455                         /* write LibData */
1456                         writestruct(wd, ID_OB, "Object", 1, ob);
1457                         
1458                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1459                          * of library blocks that implement this.*/
1460                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
1461                         
1462                         if (ob->adt) write_animdata(wd, ob->adt);
1463                         
1464                         /* direct data */
1465                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
1466                         writedata(wd, DATA, sizeof(char)*ob->totcol, ob->matbits);
1467                         /* write_effects(wd, &ob->effect); */ /* not used anymore */
1468                         write_properties(wd, &ob->prop);
1469                         write_sensors(wd, &ob->sensors);
1470                         write_controllers(wd, &ob->controllers);
1471                         write_actuators(wd, &ob->actuators);
1472
1473                         if (ob->type == OB_ARMATURE) {
1474                                 bArmature *arm = ob->data;
1475                                 if (arm && ob->pose && arm->act_bone) {
1476                                         BLI_strncpy(ob->pose->proxy_act_bone, arm->act_bone->name, sizeof(ob->pose->proxy_act_bone));
1477                                 }
1478                         }
1479
1480                         write_pose(wd, ob->pose);
1481                         write_defgroups(wd, &ob->defbase);
1482                         write_constraints(wd, &ob->constraints);
1483                         write_motionpath(wd, ob->mpath);
1484                         
1485                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
1486                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
1487                         if (ob->soft) {
1488                                 write_pointcaches(wd, &ob->soft->ptcaches);
1489                                 writestruct(wd, DATA, "EffectorWeights", 1, ob->soft->effector_weights);
1490                         }
1491                         writestruct(wd, DATA, "BulletSoftBody", 1, ob->bsoft);
1492                         
1493                         write_particlesystems(wd, &ob->particlesystem);
1494                         write_modifiers(wd, &ob->modifiers);
1495                 }
1496                 ob= ob->id.next;
1497         }
1498
1499         /* flush helps the compression for undo-save */
1500         mywrite(wd, MYWRITE_FLUSH, 0);
1501 }
1502
1503
1504 static void write_vfonts(WriteData *wd, ListBase *idbase)
1505 {
1506         VFont *vf;
1507         PackedFile * pf;
1508
1509         vf= idbase->first;
1510         while (vf) {
1511                 if (vf->id.us>0 || wd->current) {
1512                         /* write LibData */
1513                         writestruct(wd, ID_VF, "VFont", 1, vf);
1514                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
1515
1516                         /* direct data */
1517
1518                         if (vf->packedfile && !wd->current) {
1519                                 pf = vf->packedfile;
1520                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1521                                 writedata(wd, DATA, pf->size, pf->data);
1522                         }
1523                 }
1524
1525                 vf= vf->id.next;
1526         }
1527 }
1528
1529
1530 static void write_keys(WriteData *wd, ListBase *idbase)
1531 {
1532         Key *key;
1533         KeyBlock *kb;
1534
1535         key= idbase->first;
1536         while (key) {
1537                 if (key->id.us>0 || wd->current) {
1538                         /* write LibData */
1539                         writestruct(wd, ID_KE, "Key", 1, key);
1540                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
1541                         
1542                         if (key->adt) write_animdata(wd, key->adt);
1543                         
1544                         /* direct data */
1545                         kb= key->block.first;
1546                         while (kb) {
1547                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
1548                                 if (kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
1549                                 kb= kb->next;
1550                         }
1551                 }
1552
1553                 key= key->id.next;
1554         }
1555         /* flush helps the compression for undo-save */
1556         mywrite(wd, MYWRITE_FLUSH, 0);
1557 }
1558
1559 static void write_cameras(WriteData *wd, ListBase *idbase)
1560 {
1561         Camera *cam;
1562
1563         cam= idbase->first;
1564         while (cam) {
1565                 if (cam->id.us>0 || wd->current) {
1566                         /* write LibData */
1567                         writestruct(wd, ID_CA, "Camera", 1, cam);
1568                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
1569                         
1570                         if (cam->adt) write_animdata(wd, cam->adt);
1571                 }
1572
1573                 cam= cam->id.next;
1574         }
1575 }
1576
1577 static void write_mballs(WriteData *wd, ListBase *idbase)
1578 {
1579         MetaBall *mb;
1580         MetaElem *ml;
1581
1582         mb= idbase->first;
1583         while (mb) {
1584                 if (mb->id.us>0 || wd->current) {
1585                         /* write LibData */
1586                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
1587                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
1588
1589                         /* direct data */
1590                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
1591                         if (mb->adt) write_animdata(wd, mb->adt);
1592
1593                         ml= mb->elems.first;
1594                         while (ml) {
1595                                 writestruct(wd, DATA, "MetaElem", 1, ml);
1596                                 ml= ml->next;
1597                         }
1598                 }
1599                 mb= mb->id.next;
1600         }
1601 }
1602
1603 static int amount_of_chars(char *str)
1604 {
1605         // Since the data is saved as UTF-8 to the cu->str
1606         // The cu->len is not same as the strlen(cu->str)
1607         return strlen(str);
1608 }
1609
1610 static void write_curves(WriteData *wd, ListBase *idbase)
1611 {
1612         Curve *cu;
1613         Nurb *nu;
1614
1615         cu= idbase->first;
1616         while (cu) {
1617                 if (cu->id.us>0 || wd->current) {
1618                         /* write LibData */
1619                         writestruct(wd, ID_CU, "Curve", 1, cu);
1620                         
1621                         /* direct data */
1622                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
1623                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
1624                         if (cu->adt) write_animdata(wd, cu->adt);
1625                         
1626                         if (cu->vfont) {
1627                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1628                                 writestruct(wd, DATA, "CharInfo", cu->len+1, cu->strinfo);
1629                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);
1630                         }
1631                         else {
1632                                 /* is also the order of reading */
1633                                 nu= cu->nurb.first;
1634                                 while (nu) {
1635                                         writestruct(wd, DATA, "Nurb", 1, nu);
1636                                         nu= nu->next;
1637                                 }
1638                                 nu= cu->nurb.first;
1639                                 while (nu) {
1640                                         if (nu->type == CU_BEZIER)
1641                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1642                                         else {
1643                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1644                                                 if (nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1645                                                 if (nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1646                                         }
1647                                         nu= nu->next;
1648                                 }
1649                         }
1650                 }
1651                 cu= cu->id.next;
1652         }
1653
1654         /* flush helps the compression for undo-save */
1655         mywrite(wd, MYWRITE_FLUSH, 0);
1656 }
1657
1658 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1659 {
1660         if (dvlist) {
1661                 int i;
1662                 
1663                 /* Write the dvert list */
1664                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1665                 
1666                 /* Write deformation data for each dvert */
1667                 for (i=0; i<count; i++) {
1668                         if (dvlist[i].dw)
1669                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1670                 }
1671         }
1672 }
1673
1674 static void write_mdisps(WriteData *wd, int count, MDisps *mdlist, int external)
1675 {
1676         if (mdlist) {
1677                 int i;
1678                 
1679                 writestruct(wd, DATA, "MDisps", count, mdlist);
1680                 for (i = 0; i < count; ++i) {
1681                         MDisps *md = &mdlist[i];
1682                         if (md->disps) {
1683                                 if (!external)
1684                                         writedata(wd, DATA, sizeof(float) * 3 * md->totdisp, md->disps);
1685                         }
1686                         
1687                         if (md->hidden)
1688                                 writedata(wd, DATA, BLI_BITMAP_SIZE(md->totdisp), md->hidden);
1689                 }
1690         }
1691 }
1692
1693 static void write_grid_paint_mask(WriteData *wd, int count, GridPaintMask *grid_paint_mask)
1694 {
1695         if (grid_paint_mask) {
1696                 int i;
1697                 
1698                 writestruct(wd, DATA, "GridPaintMask", count, grid_paint_mask);
1699                 for (i = 0; i < count; ++i) {
1700                         GridPaintMask *gpm = &grid_paint_mask[i];
1701                         if (gpm->data) {
1702                                 const int gridsize = ccg_gridsize(gpm->level);
1703                                 writedata(wd, DATA,
1704                                           sizeof(*gpm->data) * gridsize * gridsize,
1705                                           gpm->data);
1706                         }
1707                 }
1708         }
1709 }
1710
1711 static void write_customdata(WriteData *wd, ID *id, int count, CustomData *data, int partial_type, int partial_count)
1712 {
1713         int i;
1714
1715         /* write external customdata (not for undo) */
1716         if (data->external && !wd->current)
1717                 CustomData_external_write(data, id, CD_MASK_MESH, count, 0);
1718
1719         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1720
1721         for (i=0; i<data->totlayer; i++) {
1722                 CustomDataLayer *layer= &data->layers[i];
1723                 const char *structname;
1724                 int structnum, datasize;
1725
1726                 if (layer->type == CD_MDEFORMVERT) {
1727                         /* layer types that allocate own memory need special handling */
1728                         write_dverts(wd, count, layer->data);
1729                 }
1730                 else if (layer->type == CD_MDISPS) {
1731                         write_mdisps(wd, count, layer->data, layer->flag & CD_FLAG_EXTERNAL);
1732                 }
1733                 else if (layer->type == CD_PAINT_MASK) {
1734                         float *layer_data = layer->data;
1735                         writedata(wd, DATA, sizeof(*layer_data) * count, layer_data);
1736                 }
1737                 else if (layer->type == CD_GRID_PAINT_MASK) {
1738                         write_grid_paint_mask(wd, count, layer->data);
1739                 }
1740                 else {
1741                         CustomData_file_write_info(layer->type, &structname, &structnum);
1742                         if (structnum) {
1743                                 /* when using partial visibility, the MEdge and MFace layers
1744                                  * are smaller than the original, so their type and count is
1745                                  * passed to make this work */
1746                                 if (layer->type != partial_type) datasize= structnum*count;
1747                                 else datasize= structnum*partial_count;
1748
1749                                 writestruct(wd, DATA, structname, datasize, layer->data);
1750                         }
1751                         else {
1752                                 printf("%s error: layer '%s':%d - can't be written to file\n",
1753                                        __func__, structname, layer->type);
1754                         }
1755                 }
1756         }
1757
1758         if (data->external)
1759                 writestruct(wd, DATA, "CustomDataExternal", 1, data->external);
1760 }
1761
1762 static void write_meshs(WriteData *wd, ListBase *idbase)
1763 {
1764         Mesh *mesh;
1765         int save_for_old_blender= 0;
1766
1767 #ifdef USE_BMESH_SAVE_AS_COMPAT
1768         save_for_old_blender = wd->use_mesh_compat; /* option to save with older mesh format */
1769 #endif
1770
1771         mesh= idbase->first;
1772         while (mesh) {
1773                 if (mesh->id.us>0 || wd->current) {
1774                         /* write LibData */
1775                         if (!save_for_old_blender) {
1776
1777 #ifdef USE_BMESH_SAVE_WITHOUT_MFACE
1778                                 Mesh backup_mesh = {{0}};
1779                                 /* cache only - don't write */
1780                                 backup_mesh.mface = mesh->mface;
1781                                 mesh->mface = NULL;
1782                                 /* -- */
1783                                 backup_mesh.totface = mesh->totface;
1784                                 mesh->totface = 0;
1785                                 /* -- */
1786                                 backup_mesh.fdata = mesh->fdata;
1787                                 memset(&mesh->fdata, 0, sizeof(mesh->fdata));
1788                                 /* -- */
1789 #endif /* USE_BMESH_SAVE_WITHOUT_MFACE */
1790
1791                                 writestruct(wd, ID_ME, "Mesh", 1, mesh);
1792
1793                                 /* direct data */
1794                                 if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1795                                 if (mesh->adt) write_animdata(wd, mesh->adt);
1796
1797                                 writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1798                                 writedata(wd, DATA, sizeof(MSelect) * mesh->totselect, mesh->mselect);
1799
1800                                 write_customdata(wd, &mesh->id, mesh->totvert, &mesh->vdata, -1, 0);
1801                                 write_customdata(wd, &mesh->id, mesh->totedge, &mesh->edata, -1, 0);
1802                                 /* fdata is really a dummy - written so slots align */
1803                                 write_customdata(wd, &mesh->id, mesh->totface, &mesh->fdata, -1, 0);
1804                                 write_customdata(wd, &mesh->id, mesh->totloop, &mesh->ldata, -1, 0);
1805                                 write_customdata(wd, &mesh->id, mesh->totpoly, &mesh->pdata, -1, 0);
1806
1807 #ifdef USE_BMESH_SAVE_WITHOUT_MFACE
1808                                 /* cache only - don't write */
1809                                 mesh->mface = backup_mesh.mface;
1810                                 /* -- */
1811                                 mesh->totface = backup_mesh.totface;
1812                                 /* -- */
1813                                 mesh->fdata = backup_mesh.fdata;
1814 #endif /* USE_BMESH_SAVE_WITHOUT_MFACE */
1815
1816                         }
1817                         else {
1818
1819 #ifdef USE_BMESH_SAVE_AS_COMPAT
1820
1821                                 Mesh backup_mesh = {{0}};
1822
1823                                 /* backup */
1824                                 backup_mesh.mpoly = mesh->mpoly;
1825                                 mesh->mpoly = NULL;
1826                                 /* -- */
1827                                 backup_mesh.mface = mesh->mface;
1828                                 mesh->mface = NULL;
1829                                 /* -- */
1830                                 backup_mesh.totface = mesh->totface;
1831                                 mesh->totface = 0;
1832                                 /* -- */
1833                                 backup_mesh.totpoly = mesh->totpoly;
1834                                 mesh->totpoly = 0;
1835                                 /* -- */
1836                                 backup_mesh.totloop = mesh->totloop;
1837                                 mesh->totloop = 0;
1838                                 /* -- */
1839                                 backup_mesh.fdata = mesh->fdata;
1840                                 CustomData_reset(&mesh->fdata);
1841                                 /* -- */
1842                                 backup_mesh.pdata = mesh->pdata;
1843                                 CustomData_reset(&mesh->pdata);
1844                                 /* -- */
1845                                 backup_mesh.ldata = mesh->ldata;
1846                                 CustomData_reset(&mesh->ldata);
1847                                 /* -- */
1848                                 backup_mesh.edit_btmesh = mesh->edit_btmesh;
1849                                 mesh->edit_btmesh = NULL;
1850                                 /* backup */
1851
1852
1853                                 /* now fill in polys to mfaces */
1854                                 mesh->totface = BKE_mesh_mpoly_to_mface(&mesh->fdata, &backup_mesh.ldata, &backup_mesh.pdata,
1855                                                                         mesh->totface, backup_mesh.totloop, backup_mesh.totpoly);
1856
1857                                 mesh_update_customdata_pointers(mesh, FALSE);
1858
1859                                 writestruct(wd, ID_ME, "Mesh", 1, mesh);
1860
1861                                 /* direct data */
1862                                 if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1863                                 if (mesh->adt) write_animdata(wd, mesh->adt);
1864
1865                                 writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1866                                 /* writedata(wd, DATA, sizeof(MSelect) * mesh->totselect, mesh->mselect); */ /* pre-bmesh NULL's */
1867
1868                                 write_customdata(wd, &mesh->id, mesh->totvert, &mesh->vdata, -1, 0);
1869                                 write_customdata(wd, &mesh->id, mesh->totedge, &mesh->edata, -1, 0);
1870                                 write_customdata(wd, &mesh->id, mesh->totface, &mesh->fdata, -1, 0);
1871                                 /* harmless for older blender versioins but _not_ writing these keeps file size down */
1872 #if 0
1873                                 write_customdata(wd, &mesh->id, mesh->totloop, &mesh->ldata, -1, 0);
1874                                 write_customdata(wd, &mesh->id, mesh->totpoly, &mesh->pdata, -1, 0);
1875 #endif
1876
1877                                 /* restore */
1878                                 mesh->mpoly = backup_mesh.mpoly;
1879                                 /* -- */
1880                                 mesh->mface = backup_mesh.mface;
1881                                 /* -- */
1882                                 CustomData_free(&mesh->fdata, mesh->totface);
1883                                 /* -- */
1884                                 mesh->fdata= backup_mesh.fdata;
1885                                 /* -- */
1886                                 mesh->pdata= backup_mesh.pdata;
1887                                 /* -- */
1888                                 mesh->ldata= backup_mesh.ldata;
1889                                 /* -- */
1890                                 mesh->totface = backup_mesh.totface;
1891                                 mesh->totpoly = backup_mesh.totpoly;
1892                                 mesh->totloop = backup_mesh.totloop;
1893                                 /* -- */
1894                                 mesh_update_customdata_pointers(mesh, FALSE);
1895                                 /* --*/
1896                                 mesh->edit_btmesh = backup_mesh.edit_btmesh; /* keep this after updating custom pointers */
1897                                 /* restore */
1898
1899 #endif /* USE_BMESH_SAVE_AS_COMPAT */
1900                         }
1901                 }
1902                 mesh= mesh->id.next;
1903         }
1904 }
1905
1906 static void write_lattices(WriteData *wd, ListBase *idbase)
1907 {
1908         Lattice *lt;
1909         
1910         lt= idbase->first;
1911         while (lt) {
1912                 if (lt->id.us>0 || wd->current) {
1913                         /* write LibData */
1914                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1915                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1916                         
1917                         /* write animdata */
1918                         if (lt->adt) write_animdata(wd, lt->adt);
1919                         
1920                         /* direct data */
1921                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1922                         
1923                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1924                         
1925                 }
1926                 lt= lt->id.next;
1927         }
1928 }
1929
1930 static void write_previews(WriteData *wd, PreviewImage *prv)
1931 {
1932         if (prv) {
1933                 short w = prv->w[1];
1934                 short h = prv->h[1];
1935                 unsigned int *rect = prv->rect[1];
1936                 /* don't write out large previews if not requested */
1937                 if (!(U.flag & USER_SAVE_PREVIEWS)) {
1938                         prv->w[1] = 0;
1939                         prv->h[1] = 0;
1940                         prv->rect[1] = NULL;
1941                 }
1942                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1943                 if (prv->rect[0]) writedata(wd, DATA, prv->w[0]*prv->h[0]*sizeof(unsigned int), prv->rect[0]);
1944                 if (prv->rect[1]) writedata(wd, DATA, prv->w[1]*prv->h[1]*sizeof(unsigned int), prv->rect[1]);
1945
1946                 /* restore preview, we still want to keep it in memory even if not saved to file */
1947                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1948                         prv->w[1] = w;
1949                         prv->h[1] = h;
1950                         prv->rect[1] = rect;
1951                 }
1952         }
1953 }
1954
1955 static void write_images(WriteData *wd, ListBase *idbase)
1956 {
1957         Image *ima;
1958         PackedFile * pf;
1959
1960
1961         ima= idbase->first;
1962         while (ima) {
1963                 if (ima->id.us>0 || wd->current) {
1964                         /* write LibData */
1965                         writestruct(wd, ID_IM, "Image", 1, ima);
1966                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1967
1968                         if (ima->packedfile && !wd->current) {
1969                                 pf = ima->packedfile;
1970                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1971                                 writedata(wd, DATA, pf->size, pf->data);
1972                         }
1973
1974                         write_previews(wd, ima->preview);
1975                 }
1976                 ima= ima->id.next;
1977         }
1978         /* flush helps the compression for undo-save */
1979         mywrite(wd, MYWRITE_FLUSH, 0);
1980 }
1981
1982 static void write_textures(WriteData *wd, ListBase *idbase)
1983 {
1984         Tex *tex;
1985
1986         tex= idbase->first;
1987         while (tex) {
1988                 if (tex->id.us>0 || wd->current) {
1989                         /* write LibData */
1990                         writestruct(wd, ID_TE, "Tex", 1, tex);
1991                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1992
1993                         if (tex->adt) write_animdata(wd, tex->adt);
1994
1995                         /* direct data */
1996                         if (tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1997                         if (tex->type == TEX_ENVMAP && tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1998                         if (tex->type == TEX_POINTDENSITY && tex->pd) {
1999                                 writestruct(wd, DATA, "PointDensity", 1, tex->pd);
2000                                 if (tex->pd->coba) writestruct(wd, DATA, "ColorBand", 1, tex->pd->coba);
2001                                 if (tex->pd->falloff_curve) write_curvemapping(wd, tex->pd->falloff_curve);
2002                         }
2003                         if (tex->type == TEX_VOXELDATA) writestruct(wd, DATA, "VoxelData", 1, tex->vd);
2004                         if (tex->type == TEX_OCEAN && tex->ot) writestruct(wd, DATA, "OceanTex", 1, tex->ot);
2005                         
2006                         /* nodetree is integral part of texture, no libdata */
2007                         if (tex->nodetree) {
2008                                 writestruct(wd, DATA, "bNodeTree", 1, tex->nodetree);
2009                                 write_nodetree(wd, tex->nodetree);
2010                         }
2011                         
2012                         write_previews(wd, tex->preview);
2013                 }
2014                 tex= tex->id.next;
2015         }
2016
2017         /* flush helps the compression for undo-save */
2018         mywrite(wd, MYWRITE_FLUSH, 0);
2019 }
2020
2021 static void write_materials(WriteData *wd, ListBase *idbase)
2022 {
2023         Material *ma;
2024         int a;
2025
2026         ma= idbase->first;
2027         while (ma) {
2028                 if (ma->id.us>0 || wd->current) {
2029                         /* write LibData */
2030                         writestruct(wd, ID_MA, "Material", 1, ma);
2031                         
2032                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
2033                          * of library blocks that implement this.*/
2034                         /* manually set head group property to IDP_GROUP, just in case it hadn't been
2035                          * set yet :) */
2036                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
2037                         
2038                         if (ma->adt) write_animdata(wd, ma->adt);
2039
2040                         for (a=0; a<MAX_MTEX; a++) {
2041                                 if (ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
2042                         }
2043                         
2044                         if (ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
2045                         if (ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
2046                         
2047                         /* nodetree is integral part of material, no libdata */
2048                         if (ma->nodetree) {
2049                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
2050                                 write_nodetree(wd, ma->nodetree);
2051                         }
2052
2053                         write_previews(wd, ma->preview);
2054                 }
2055                 ma= ma->id.next;
2056         }
2057 }
2058
2059 static void write_worlds(WriteData *wd, ListBase *idbase)
2060 {
2061         World *wrld;
2062         int a;
2063
2064         wrld= idbase->first;
2065         while (wrld) {
2066                 if (wrld->id.us>0 || wd->current) {
2067                         /* write LibData */
2068                         writestruct(wd, ID_WO, "World", 1, wrld);
2069                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
2070                         
2071                         if (wrld->adt) write_animdata(wd, wrld->adt);
2072                         
2073                         for (a=0; a<MAX_MTEX; a++) {
2074                                 if (wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
2075                         }
2076
2077                         /* nodetree is integral part of lamps, no libdata */
2078                         if (wrld->nodetree) {
2079                                 writestruct(wd, DATA, "bNodeTree", 1, wrld->nodetree);
2080                                 write_nodetree(wd, wrld->nodetree);
2081                         }
2082                         
2083                         write_previews(wd, wrld->preview);
2084                 }
2085                 wrld= wrld->id.next;
2086         }
2087 }
2088
2089 static void write_lamps(WriteData *wd, ListBase *idbase)
2090 {
2091         Lamp *la;
2092         int a;
2093
2094         la= idbase->first;
2095         while (la) {
2096                 if (la->id.us>0 || wd->current) {
2097                         /* write LibData */
2098                         writestruct(wd, ID_LA, "Lamp", 1, la);
2099                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
2100                         
2101                         if (la->adt) write_animdata(wd, la->adt);
2102                         
2103                         /* direct data */
2104                         for (a=0; a<MAX_MTEX; a++) {
2105                                 if (la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
2106                         }
2107                         
2108                         if (la->curfalloff)
2109                                 write_curvemapping(wd, la->curfalloff);
2110                         
2111                         /* nodetree is integral part of lamps, no libdata */
2112                         if (la->nodetree) {
2113                                 writestruct(wd, DATA, "bNodeTree", 1, la->nodetree);
2114                                 write_nodetree(wd, la->nodetree);
2115                         }
2116
2117                         write_previews(wd, la->preview);
2118                         
2119                 }
2120                 la= la->id.next;
2121         }
2122 }
2123
2124 static void write_sequence_modifiers(WriteData *wd, ListBase *modbase)
2125 {
2126         SequenceModifierData *smd;
2127
2128         for (smd = modbase->first; smd; smd = smd->next) {
2129                 SequenceModifierTypeInfo *smti = BKE_sequence_modifier_type_info_get(smd->type);
2130
2131                 if (smti) {
2132                         writestruct(wd, DATA, smti->struct_name, 1, smd);
2133
2134                         if (smd->type == seqModifierType_Curves) {
2135                                 CurvesModifierData *cmd = (CurvesModifierData *) smd;
2136
2137                                 write_curvemapping(wd, &cmd->curve_mapping);
2138                         }
2139                         else if (smd->type == seqModifierType_HueCorrect) {
2140                                 HueCorrectModifierData *hcmd = (HueCorrectModifierData *) smd;
2141
2142                                 write_curvemapping(wd, &hcmd->curve_mapping);
2143                         }
2144                 }
2145                 else {
2146                         writestruct(wd, DATA, "SequenceModifierData", 1, smd);
2147                 }
2148         }
2149 }
2150
2151 static void write_view_settings(WriteData *wd, ColorManagedViewSettings *view_settings)
2152 {
2153         if (view_settings->curve_mapping) {
2154                 write_curvemapping(wd, view_settings->curve_mapping);
2155         }
2156 }
2157
2158 static void write_scenes(WriteData *wd, ListBase *scebase)
2159 {
2160         Scene *sce;
2161         Base *base;
2162         Editing *ed;
2163         Sequence *seq;
2164         MetaStack *ms;
2165         Strip *strip;
2166         TimeMarker *marker;
2167         TransformOrientation *ts;
2168         SceneRenderLayer *srl;
2169         ToolSettings *tos;
2170         
2171         sce= scebase->first;
2172         while (sce) {
2173                 /* write LibData */
2174                 writestruct(wd, ID_SCE, "Scene", 1, sce);
2175                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
2176                 
2177                 if (sce->adt) write_animdata(wd, sce->adt);
2178                 write_keyingsets(wd, &sce->keyingsets);
2179                 
2180                 /* direct data */
2181                 base= sce->base.first;
2182                 while (base) {
2183                         writestruct(wd, DATA, "Base", 1, base);
2184                         base= base->next;
2185                 }
2186                 
2187                 tos = sce->toolsettings;
2188                 writestruct(wd, DATA, "ToolSettings", 1, tos);
2189                 if (tos->vpaint) {
2190                         writestruct(wd, DATA, "VPaint", 1, tos->vpaint);
2191                 }
2192                 if (tos->wpaint) {
2193                         writestruct(wd, DATA, "VPaint", 1, tos->wpaint);
2194                 }
2195                 if (tos->sculpt) {
2196                         writestruct(wd, DATA, "Sculpt", 1, tos->sculpt);
2197                 }
2198                 if (tos->uvsculpt) {
2199                         writestruct(wd, DATA, "UvSculpt", 1, tos->uvsculpt);
2200                 }
2201
2202                 // write_paint(wd, &tos->imapaint.paint);
2203
2204                 ed= sce->ed;
2205                 if (ed) {
2206                         writestruct(wd, DATA, "Editing", 1, ed);
2207                         
2208                         /* reset write flags too */
2209                         
2210                         SEQ_BEGIN (ed, seq)
2211                         {
2212                                 if (seq->strip) seq->strip->done = FALSE;
2213                                 writestruct(wd, DATA, "Sequence", 1, seq);
2214                         }
2215                         SEQ_END
2216                         
2217                         SEQ_BEGIN (ed, seq)
2218                         {
2219                                 if (seq->strip && seq->strip->done==0) {
2220                                         /* write strip with 'done' at 0 because readfile */
2221                                         
2222                                         if (seq->effectdata) {
2223                                                 switch (seq->type) {
2224                                                 case SEQ_TYPE_COLOR:
2225                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
2226                                                         break;
2227                                                 case SEQ_TYPE_SPEED:
2228                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
2229                                                         break;
2230                                                 case SEQ_TYPE_WIPE:
2231                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
2232                                                         break;
2233                                                 case SEQ_TYPE_GLOW:
2234                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
2235                                                         break;
2236                                                 case SEQ_TYPE_TRANSFORM:
2237                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
2238                                                         break;
2239                                                 }
2240                                         }
2241                                         
2242                                         strip= seq->strip;
2243                                         writestruct(wd, DATA, "Strip", 1, strip);
2244                                         if (seq->flag & SEQ_USE_CROP && strip->crop) {
2245                                                 writestruct(wd, DATA, "StripCrop", 1, strip->crop);
2246                                         }
2247                                         if (seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
2248                                                 writestruct(wd, DATA, "StripTransform", 1, strip->transform);
2249                                         }
2250                                         if (seq->flag & SEQ_USE_PROXY && strip->proxy) {
2251                                                 writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
2252                                         }
2253                                         if (seq->type==SEQ_TYPE_IMAGE)
2254                                                 writestruct(wd, DATA, "StripElem", MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem), strip->stripdata);
2255                                         else if (seq->type==SEQ_TYPE_MOVIE || seq->type==SEQ_TYPE_SOUND_RAM || seq->type == SEQ_TYPE_SOUND_HD)
2256                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
2257                                         
2258                                         strip->done = TRUE;
2259                                 }
2260
2261                                 write_sequence_modifiers(wd, &seq->modifiers);
2262                         }
2263                         SEQ_END
2264                                 
2265                         /* new; meta stack too, even when its nasty restore code */
2266                         for (ms= ed->metastack.first; ms; ms= ms->next) {
2267                                 writestruct(wd, DATA, "MetaStack", 1, ms);
2268                         }
2269                 }
2270                 
2271                 if (sce->r.avicodecdata) {
2272                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
2273                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
2274                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
2275                 }
2276
2277                 if (sce->r.qtcodecdata) {
2278                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
2279                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
2280                 }
2281                 if (sce->r.ffcodecdata.properties) {
2282                         IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
2283                 }
2284
2285                 /* writing dynamic list of TimeMarkers to the blend file */
2286                 for (marker= sce->markers.first; marker; marker= marker->next)
2287                         writestruct(wd, DATA, "TimeMarker", 1, marker);
2288                 
2289                 /* writing dynamic list of TransformOrientations to the blend file */
2290                 for (ts = sce->transform_spaces.first; ts; ts = ts->next)
2291                         writestruct(wd, DATA, "TransformOrientation", 1, ts);
2292                 
2293                 for (srl = sce->r.layers.first; srl; srl = srl->next) {
2294                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
2295                         
2296 #ifdef WITH_FREESTYLE
2297                         {
2298                                 FreestyleModuleConfig *fmc;
2299                                 FreestyleLineSet *fls;
2300
2301                                 for(fmc = srl->freestyleConfig.modules.first; fmc; fmc = fmc->next) {
2302                                         writestruct(wd, DATA, "FreestyleModuleConfig", 1, fmc);
2303                                 }
2304                         
2305                                 for(fls = srl->freestyleConfig.linesets.first; fls; fls = fls->next) {
2306                                         writestruct(wd, DATA, "FreestyleLineSet", 1, fls);
2307                                 }
2308
2309                         }
2310 #endif
2311                 }
2312                 
2313                 if (sce->nodetree) {
2314                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
2315                         write_nodetree(wd, sce->nodetree);
2316                 }
2317
2318                 write_view_settings(wd, &sce->view_settings);
2319
2320                 sce= sce->id.next;
2321         }
2322         /* flush helps the compression for undo-save */
2323         mywrite(wd, MYWRITE_FLUSH, 0);
2324 }
2325
2326 static void write_gpencils(WriteData *wd, ListBase *lb)
2327 {
2328         bGPdata *gpd;
2329         bGPDlayer *gpl;
2330         bGPDframe *gpf;
2331         bGPDstroke *gps;
2332         
2333         for (gpd= lb->first; gpd; gpd= gpd->id.next) {
2334                 if (gpd->id.us>0 || wd->current) {
2335                         /* write gpd data block to file */
2336                         writestruct(wd, ID_GD, "bGPdata", 1, gpd);
2337                         
2338                         /* write grease-pencil layers to file */
2339                         for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
2340                                 writestruct(wd, DATA, "bGPDlayer", 1, gpl);
2341                                 
2342                                 /* write this layer's frames to file */
2343                                 for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
2344                                         writestruct(wd, DATA, "bGPDframe", 1, gpf);
2345                                         
2346                                         /* write strokes */
2347                                         for (gps= gpf->strokes.first; gps; gps= gps->next) {
2348                                                 writestruct(wd, DATA, "bGPDstroke", 1, gps);
2349                                                 writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);
2350                                         }
2351                                 }
2352                         }
2353                 }
2354         }
2355 }
2356
2357 static void write_windowmanagers(WriteData *wd, ListBase *lb)
2358 {
2359         wmWindowManager *wm;
2360         wmWindow *win;
2361         
2362         for (wm= lb->first; wm; wm= wm->id.next) {
2363                 writestruct(wd, ID_WM, "wmWindowManager", 1, wm);
2364                 
2365                 for (win= wm->windows.first; win; win= win->next)
2366                         writestruct(wd, DATA, "wmWindow", 1, win);
2367         }
2368 }
2369
2370 static void write_region(WriteData *wd, ARegion *ar, int spacetype)
2371 {       
2372         writestruct(wd, DATA, "ARegion", 1, ar);
2373         
2374         if (ar->regiondata) {
2375                 switch (spacetype) {
2376                         case SPACE_VIEW3D:
2377                                 if (ar->regiontype==RGN_TYPE_WINDOW) {
2378                                         RegionView3D *rv3d= ar->regiondata;
2379                                         writestruct(wd, DATA, "RegionView3D", 1, rv3d);
2380                                         
2381                                         if (rv3d->localvd)
2382                                                 writestruct(wd, DATA, "RegionView3D", 1, rv3d->localvd);
2383                                         if (rv3d->clipbb)
2384                                                 writestruct(wd, DATA, "BoundBox", 1, rv3d->clipbb);
2385
2386                                 }
2387                                 else
2388                                         printf("regiondata write missing!\n");
2389                                 break;
2390                         default:
2391                                 printf("regiondata write missing!\n");
2392                 }
2393         }
2394 }
2395
2396 static void write_screens(WriteData *wd, ListBase *scrbase)
2397 {
2398         bScreen *sc;
2399         ScrArea *sa;
2400         ScrVert *sv;
2401         ScrEdge *se;
2402
2403         sc= scrbase->first;
2404         while (sc) {
2405                 
2406                 /* write LibData */
2407                 /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
2408                 writestruct(wd, ID_SCRN, "Screen", 1, sc);
2409                 if (sc->id.properties) 
2410                         IDP_WriteProperty(sc->id.properties, wd);
2411                 
2412                 /* direct data */
2413                 for (sv= sc->vertbase.first; sv; sv= sv->next)
2414                         writestruct(wd, DATA, "ScrVert", 1, sv);
2415                 
2416                 for (se= sc->edgebase.first; se; se= se->next)
2417                         writestruct(wd, DATA, "ScrEdge", 1, se);
2418                 
2419                 for (sa= sc->areabase.first; sa; sa= sa->next) {
2420                         SpaceLink *sl;
2421                         Panel *pa;
2422                         uiList *ui_list;
2423                         ARegion *ar;
2424                         
2425                         writestruct(wd, DATA, "ScrArea", 1, sa);
2426                         
2427                         for (ar= sa->regionbase.first; ar; ar= ar->next) {
2428                                 write_region(wd, ar, sa->spacetype);
2429                                 
2430                                 for (pa= ar->panels.first; pa; pa= pa->next)
2431                                         writestruct(wd, DATA, "Panel", 1, pa);
2432                                 
2433                                 for (ui_list = ar->ui_lists.first; ui_list; ui_list = ui_list->next)
2434                                         writestruct(wd, DATA, "uiList", 1, ui_list);
2435                         }
2436                         
2437                         sl= sa->spacedata.first;
2438                         while (sl) {
2439                                 for (ar= sl->regionbase.first; ar; ar= ar->next)
2440                                         write_region(wd, ar, sl->spacetype);
2441                                 
2442                                 if (sl->spacetype==SPACE_VIEW3D) {
2443                                         View3D *v3d= (View3D *) sl;
2444                                         BGpic *bgpic;
2445                                         writestruct(wd, DATA, "View3D", 1, v3d);
2446                                         for (bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next)
2447                                                 writestruct(wd, DATA, "BGpic", 1, bgpic);
2448                                         if (v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
2449                                 }
2450                                 else if (sl->spacetype==SPACE_IPO) {
2451                                         SpaceIpo *sipo= (SpaceIpo *)sl;
2452                                         ListBase tmpGhosts = sipo->ghostCurves;
2453                                         
2454                                         /* temporarily disable ghost curves when saving */
2455                                         sipo->ghostCurves.first= sipo->ghostCurves.last= NULL;
2456                                         
2457                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
2458                                         if (sipo->ads) writestruct(wd, DATA, "bDopeSheet", 1, sipo->ads);
2459                                         
2460                                         /* reenable ghost curves */
2461                                         sipo->ghostCurves= tmpGhosts;
2462                                 }
2463                                 else if (sl->spacetype==SPACE_BUTS) {
2464                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
2465                                 }
2466                                 else if (sl->spacetype==SPACE_FILE) {
2467                                         SpaceFile *sfile= (SpaceFile *)sl;
2468
2469                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
2470                                         if (sfile->params)
2471                                                 writestruct(wd, DATA, "FileSelectParams", 1, sfile->params);
2472                                 }
2473                                 else if (sl->spacetype==SPACE_SEQ) {
2474                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
2475                                 }
2476                                 else if (sl->spacetype==SPACE_OUTLINER) {
2477                                         SpaceOops *so= (SpaceOops *)sl;
2478                                         
2479                                         writestruct(wd, DATA, "SpaceOops", 1, so);
2480
2481                                         /* outliner */
2482                                         if (so->treestore) {
2483                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
2484                                                 if (so->treestore->data)
2485                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
2486                                         }
2487                                 }
2488                                 else if (sl->spacetype==SPACE_IMAGE) {
2489                                         SpaceImage *sima= (SpaceImage *)sl;
2490                                         
2491                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
2492                                         if (sima->cumap)
2493                                                 write_curvemapping(wd, sima->cumap);
2494                                 }
2495                                 else if (sl->spacetype==SPACE_TEXT) {
2496                                         writestruct(wd, DATA, "SpaceText", 1, sl);
2497                                 }
2498                                 else if (sl->spacetype==SPACE_SCRIPT) {
2499                                         SpaceScript *scr = (SpaceScript*)sl;
2500                                         scr->but_refs = NULL;
2501                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
2502                                 }
2503                                 else if (sl->spacetype==SPACE_ACTION) {
2504                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
2505                                 }
2506                                 else if (sl->spacetype==SPACE_NLA) {
2507                                         SpaceNla *snla= (SpaceNla *)sl;
2508                                         
2509                                         writestruct(wd, DATA, "SpaceNla", 1, snla);
2510                                         if (snla->ads) writestruct(wd, DATA, "bDopeSheet", 1, snla->ads);
2511                                 }
2512                                 else if (sl->spacetype==SPACE_TIME) {
2513                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
2514                                 }
2515                                 else if (sl->spacetype==SPACE_NODE) {
2516                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
2517                                 }
2518                                 else if (sl->spacetype==SPACE_LOGIC) {
2519                                         writestruct(wd, DATA, "SpaceLogic", 1, sl);
2520                                 }
2521                                 else if (sl->spacetype==SPACE_CONSOLE) {
2522                                         SpaceConsole *con = (SpaceConsole*)sl;
2523                                         ConsoleLine *cl;
2524
2525                                         for (cl=con->history.first; cl; cl=cl->next) {
2526                                                 /* 'len_alloc' is invalid on write, set from 'len' on read */
2527                                                 writestruct(wd, DATA, "ConsoleLine", 1, cl);
2528                                                 writedata(wd, DATA, cl->len+1, cl->line);
2529                                         }
2530                                         writestruct(wd, DATA, "SpaceConsole", 1, sl);
2531
2532                                 }
2533                                 else if (sl->spacetype==SPACE_USERPREF) {
2534                                         writestruct(wd, DATA, "SpaceUserPref", 1, sl);
2535                                 }
2536                                 else if (sl->spacetype==SPACE_CLIP) {
2537                                         writestruct(wd, DATA, "SpaceClip", 1, sl);
2538                                 }
2539
2540                                 sl= sl->next;
2541                         }
2542                 }
2543
2544                 sc= sc->id.next;
2545         }
2546         
2547         /* flush helps the compression for undo-save */
2548         mywrite(wd, MYWRITE_FLUSH, 0);
2549 }
2550
2551 static void write_libraries(WriteData *wd, Main *main)
2552 {
2553         ListBase *lbarray[MAX_LIBARRAY];
2554         ID *id;
2555         int a, tot, foundone;
2556
2557         for (; main; main= main->next) {
2558
2559                 a=tot= set_listbasepointers(main, lbarray);
2560
2561                 /* test: is lib being used */
2562                 if (main->curlib && main->curlib->packedfile)
2563                         foundone = TRUE;
2564                 else {
2565                         foundone = FALSE;
2566                         while (tot--) {
2567                                 for (id= lbarray[tot]->first; id; id= id->next) {
2568                                         if (id->us>0 && (id->flag & LIB_EXTERN)) {
2569                                                 foundone = TRUE;
2570                                                 break;
2571                                         }
2572                                 }
2573                                 if (foundone) break;
2574                         }
2575                 }
2576                 
2577                 if (foundone) {
2578                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
2579
2580                         if (main->curlib->packedfile && !wd->current) {
2581                                 PackedFile *pf = main->curlib->packedfile;
2582                                 writestruct(wd, DATA, "PackedFile", 1, pf);
2583                                 writedata(wd, DATA, pf->size, pf->data);
2584                                 printf("write packed .blend: %s\n", main->curlib->name);
2585                         }
2586                         
2587                         while (a--) {
2588                                 for (id= lbarray[a]->first; id; id= id->next) {
2589                                         if (id->us>0 && (id->flag & LIB_EXTERN)) {
2590                                                 writestruct(wd, ID_ID, "ID", 1, id);
2591                                         }
2592                                 }
2593                         }
2594                 }
2595         }
2596 }
2597
2598 static void write_bone(WriteData *wd, Bone *bone)
2599 {
2600         Bone*   cbone;
2601
2602         // PATCH for upward compatibility after 2.37+ armature recode
2603         bone->size[0] = bone->size[1] = bone->size[2] = 1.0f;
2604                 
2605         // Write this bone
2606         writestruct(wd, DATA, "Bone", 1, bone);
2607
2608         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
2609          * of library blocks that implement this.*/
2610         if (bone->prop)
2611                 IDP_WriteProperty(bone->prop, wd);
2612         
2613         // Write Children
2614         cbone= bone->childbase.first;
2615         while (cbone) {
2616                 write_bone(wd, cbone);
2617                 cbone= cbone->next;
2618         }
2619 }
2620
2621 static void write_armatures(WriteData *wd, ListBase *idbase)
2622 {
2623         bArmature       *arm;
2624         Bone            *bone;
2625
2626         arm=idbase->first;
2627         while (arm) {
2628                 if (arm->id.us>0 || wd->current) {
2629                         writestruct(wd, ID_AR, "bArmature", 1, arm);
2630                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
2631
2632                         if (arm->adt) write_animdata(wd, arm->adt);
2633
2634                         /* Direct data */
2635                         bone= arm->bonebase.first;
2636                         while (bone) {
2637                                 write_bone(wd, bone);
2638                                 bone=bone->next;
2639                         }
2640                 }
2641                 arm=arm->id.next;
2642         }
2643
2644         /* flush helps the compression for undo-save */
2645         mywrite(wd, MYWRITE_FLUSH, 0);
2646 }
2647
2648 static void write_texts(WriteData *wd, ListBase *idbase)
2649 {
2650         Text *text;
2651         TextLine *tmp;
2652
2653         text= idbase->first;
2654         while (text) {
2655                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
2656
2657                 /* write LibData */
2658                 writestruct(wd, ID_TXT, "Text", 1, text);
2659                 if (text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
2660                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
2661
2662                 if (!(text->flags & TXT_ISEXT)) {
2663                         /* now write the text data, in two steps for optimization in the readfunction */
2664                         tmp= text->lines.first;
2665                         while (tmp) {
2666                                 writestruct(wd, DATA, "TextLine", 1, tmp);
2667                                 tmp= tmp->next;
2668                         }
2669
2670                         tmp= text->lines.first;
2671                         while (tmp) {
2672                                 writedata(wd, DATA, tmp->len+1, tmp->line);
2673                                 tmp= tmp->next;
2674                         }
2675                 }
2676
2677
2678                 text= text->id.next;
2679         }
2680
2681         /* flush helps the compression for undo-save */
2682         mywrite(wd, MYWRITE_FLUSH, 0);
2683 }
2684
2685 static void write_speakers(WriteData *wd, ListBase *idbase)
2686 {
2687         Speaker *spk;
2688
2689         spk= idbase->first;
2690         while (spk) {
2691                 if (spk->id.us>0 || wd->current) {
2692                         /* write LibData */
2693                         writestruct(wd, ID_SPK, "Speaker", 1, spk);
2694                         if (spk->id.properties) IDP_WriteProperty(spk->id.properties, wd);
2695
2696                         if (spk->adt) write_animdata(wd, spk->adt);
2697                 }
2698                 spk= spk->id.next;
2699         }
2700 }
2701
2702 static void write_sounds(WriteData *wd, ListBase *idbase)
2703 {
2704         bSound *sound;
2705
2706         PackedFile * pf;
2707
2708         sound= idbase->first;
2709         while (sound) {
2710                 if (sound->id.us>0 || wd->current) {
2711                         /* write LibData */
2712                         writestruct(wd, ID_SO, "bSound", 1, sound);
2713                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
2714
2715                         if (sound->packedfile && !wd->current) {
2716                                 pf = sound->packedfile;
2717                                 writestruct(wd, DATA, "PackedFile", 1, pf);
2718                                 writedata(wd, DATA, pf->size, pf->data);
2719                         }
2720                 }
2721                 sound= sound->id.next;
2722         }
2723
2724         /* flush helps the compression for undo-save */
2725         mywrite(wd, MYWRITE_FLUSH, 0);
2726 }
2727
2728 static void write_groups(WriteData *wd, ListBase *idbase)
2729 {
2730         Group *group;
2731         GroupObject *go;
2732
2733         for (group= idbase->first; group; group= group->id.next) {
2734                 if (group->id.us>0 || wd->current) {
2735                         /* write LibData */
2736                         writestruct(wd, ID_GR, "Group", 1, group);
2737                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
2738
2739                         go= group->gobject.first;
2740                         while (go) {
2741                                 writestruct(wd, DATA, "GroupObject", 1, go);
2742                                 go= go->next;
2743                         }
2744                 }
2745         }
2746 }
2747
2748 static void write_nodetrees(WriteData *wd, ListBase *idbase)
2749 {
2750         bNodeTree *ntree;
2751         
2752         for (ntree=idbase->first; ntree; ntree= ntree->id.next) {
2753                 if (ntree->id.us>0 || wd->current) {
2754                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
2755                         write_nodetree(wd, ntree);
2756                         
2757                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
2758                         
2759                         if (ntree->adt) write_animdata(wd, ntree->adt);
2760                 }
2761         }
2762 }
2763
2764 static void write_brushes(WriteData *wd, ListBase *idbase)
2765 {
2766         Brush *brush;
2767         
2768         for (brush=idbase->first; brush; brush= brush->id.next) {
2769                 if (brush->id.us>0 || wd->current) {
2770                         writestruct(wd, ID_BR, "Brush", 1, brush);
2771                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
2772                         
2773                         writestruct(wd, DATA, "MTex", 1, &brush->mtex);
2774                         
2775                         if (brush->curve)
2776                                 write_curvemapping(wd, brush->curve);
2777                 }
2778         }
2779 }
2780
2781 static void write_scripts(WriteData *wd, ListBase *idbase)
2782 {
2783         Script *script;
2784         
2785         for (script=idbase->first; script; script= script->id.next) {
2786                 if (script->id.us>0 || wd->current) {
2787                         writestruct(wd, ID_SCRIPT, "Script", 1, script);
2788                         if (script->id.properties) IDP_WriteProperty(script->id.properties, wd);
2789                 }
2790         }
2791 }
2792
2793 static void write_movieTracks(WriteData *wd, ListBase *tracks)
2794 {
2795         MovieTrackingTrack *track;
2796
2797         track= tracks->first;
2798         while (track) {
2799                 writestruct(wd, DATA, "MovieTrackingTrack", 1, track);
2800
2801                 if (track->markers)
2802                         writestruct(wd, DATA, "MovieTrackingMarker", track->markersnr, track->markers);
2803
2804                 track= track->next;
2805         }
2806 }
2807
2808 static void write_movieReconstruction(WriteData *wd, MovieTrackingReconstruction *reconstruction)
2809 {
2810         if (reconstruction->camnr)
2811                 writestruct(wd, DATA, "MovieReconstructedCamera", reconstruction->camnr, reconstruction->cameras);
2812 }
2813
2814 static void write_movieclips(WriteData *wd, ListBase *idbase)
2815 {
2816         MovieClip *clip;
2817
2818         clip= idbase->first;
2819         while (clip) {
2820                 if (clip->id.us>0 || wd->current) {
2821                         MovieTracking *tracking= &clip->tracking;
2822                         MovieTrackingObject *object;
2823                         writestruct(wd, ID_MC, "MovieClip", 1, clip);
2824
2825                         if (clip->id.properties)
2826                                 IDP_WriteProperty(clip->id.properties, wd);
2827
2828                         if (clip->adt)
2829                                 write_animdata(wd, clip->adt);
2830
2831                         write_movieTracks(wd, &tracking->tracks);
2832                         write_movieReconstruction(wd, &tracking->reconstruction);
2833
2834                         object= tracking->objects.first;
2835                         while (object) {
2836                                 writestruct(wd, DATA, "MovieTrackingObject", 1, object);
2837
2838                                 write_movieTracks(wd, &object->tracks);
2839                                 write_movieReconstruction(wd, &object->reconstruction);
2840
2841                                 object= object->next;
2842                         }
2843                 }
2844
2845                 clip= clip->id.next;
2846         }
2847
2848         /* flush helps the compression for undo-save */
2849         mywrite(wd, MYWRITE_FLUSH, 0);
2850 }
2851
2852 static void write_masks(WriteData *wd, ListBase *idbase)
2853 {
2854         Mask *mask;
2855
2856         mask = idbase->first;
2857         while (mask) {
2858                 if (mask->id.us > 0 || wd->current) {
2859                         MaskLayer *masklay;
2860
2861                         writestruct(wd, ID_MSK, "Mask", 1, mask);
2862
2863                         if (mask->adt)
2864                                 write_animdata(wd, mask->adt);
2865
2866                         for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
2867                                 MaskSpline *spline;
2868                                 MaskLayerShape *masklay_shape;
2869
2870                                 writestruct(wd, DATA, "MaskLayer", 1, masklay);
2871
2872                                 for (spline = masklay->splines.first; spline; spline = spline->next) {
2873                                         int i;
2874
2875                                         void *points_deform = spline->points_deform;
2876                                         spline->points_deform = NULL;
2877
2878                                         writestruct(wd, DATA, "MaskSpline", 1, spline);
2879                                         writestruct(wd, DATA, "MaskSplinePoint", spline->tot_point, spline->points);
2880
2881                                         spline->points_deform = points_deform;
2882
2883                                         for (i = 0; i < spline->tot_point; i++) {
2884                                                 MaskSplinePoint *point = &spline->points[i];
2885
2886                                                 if (point->tot_uw)
2887                                                         writestruct(wd, DATA, "MaskSplinePointUW", point->tot_uw, point->uw);
2888                                         }
2889                                 }
2890
2891                                 for (masklay_shape = masklay->splines_shapes.first; masklay_shape; masklay_shape = masklay_shape->next) {
2892                                         writestruct(wd, DATA, "MaskLayerShape", 1, masklay_shape);
2893                                         writedata(wd, DATA, masklay_shape->tot_vert * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE, masklay_shape->data);
2894                                 }
2895                         }
2896                 }
2897
2898                 mask = mask->id.next;
2899         }
2900
2901         /* flush helps the compression for undo-save */
2902         mywrite(wd, MYWRITE_FLUSH, 0);
2903 }
2904
2905 #ifdef WITH_FREESTYLE
2906 static void write_linestyle_color_modifiers(WriteData *wd, ListBase *modifiers)
2907 {
2908         LineStyleModifier *m;
2909         const char *struct_name;
2910
2911         for (m = modifiers->first; m; m = m->next) {
2912                 switch (m->type) {
2913                 case LS_MODIFIER_ALONG_STROKE:
2914                         struct_name = "LineStyleColorModifier_AlongStroke";
2915                         break;
2916                 case LS_MODIFIER_DISTANCE_FROM_CAMERA:
2917                         struct_name = "LineStyleColorModifier_DistanceFromCamera";
2918                         break;
2919                 case LS_MODIFIER_DISTANCE_FROM_OBJECT:
2920                         struct_name = "LineStyleColorModifier_DistanceFromObject";
2921                         break;
2922                 case LS_MODIFIER_MATERIAL:
2923                         struct_name = "LineStyleColorModifier_Material";
2924                         break;
2925                 default:
2926                         struct_name = "LineStyleColorModifier"; /* this should not happen */
2927                 }
2928                 writestruct(wd, DATA, struct_name, 1, m);
2929         }
2930         for (m = modifiers->first; m; m = m->next) {
2931                 switch (m->type) {
2932                 case LS_MODIFIER_ALONG_STROKE:
2933                         writestruct(wd, DATA, "ColorBand", 1, ((LineStyleColorModifier_AlongStroke *)m)->color_ramp);
2934                         break;
2935                 case LS_MODIFIER_DISTANCE_FROM_CAMERA:
2936                         writestruct(wd, DATA, "ColorBand", 1, ((LineStyleColorModifier_DistanceFromCamera *)m)->color_ramp);
2937                         break;
2938                 case LS_MODIFIER_DISTANCE_FROM_OBJECT:
2939                         writestruct(wd, DATA, "ColorBand", 1, ((LineStyleColorModifier_DistanceFromObject *)m)->color_ramp);
2940                         break;
2941                 case LS_MODIFIER_MATERIAL:
2942                         writestruct(wd, DATA, "ColorBand", 1, ((LineStyleColorModifier_Material *)m)->color_ramp);
2943                         break;
2944                 }
2945         }
2946 }
2947
2948 static void write_linestyle_alpha_modifiers(WriteData *wd, ListBase *modifiers)
2949 {
2950         LineStyleModifier *m;
2951         const char *struct_name;
2952
2953         for (m = modifiers->first; m; m = m->next) {
2954                 switch (m->type) {
2955                 case LS_MODIFIER_ALONG_STROKE:
2956                         struct_name = "LineStyleAlphaModifier_AlongStroke";
2957                         break;
2958                 case LS_MODIFIER_DISTANCE_FROM_CAMERA: