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