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