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