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