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