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