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