2.5/Sculpt:
[blender.git] / source / blender / blenloader / intern / writefile.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  *
24  * Contributor(s): Blender Foundation
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /*
30 FILEFORMAT: IFF-style structure  (but not IFF compatible!)
31
32 start file:
33         BLENDER_V100    12 bytes  (versie 1.00)
34                                         V = big endian, v = little endian
35                                         _ = 4 byte pointer, - = 8 byte pointer
36
37 datablocks:             also see struct BHead
38         <bh.code>                       4 chars
39         <bh.len>                        int,  len data after BHead
40         <bh.old>                        void,  old pointer
41         <bh.SDNAnr>                     int
42         <bh.nr>                         int, in case of array: amount of structs
43         data
44         ...
45         ...
46
47 Almost all data in Blender are structures. Each struct saved
48 gets a BHead header.  With BHead the struct can be linked again
49 and compared with StructDNA .
50
51 WRITE
52
53 Preferred writing order: (not really a must, but why would you do it random?)
54 Any case: direct data is ALWAYS after the lib block
55
56 (Local file data)
57 - for each LibBlock
58         - write LibBlock
59         - write associated direct data
60 (External file data)
61 - per library
62         - write library block
63         - per LibBlock
64                 - write the ID of LibBlock
65 - write FileGlobal (some global vars)
66 - write SDNA
67 - write USER if filename is ~/.B.blend
68 */
69
70
71 #ifdef HAVE_CONFIG_H
72 #include <config.h>
73 #endif
74
75 #include "zlib.h"
76
77 #ifndef WIN32
78 #include <unistd.h>
79 #else
80 #include "winsock2.h"
81 #include "BLI_winstuff.h"
82 #include <io.h>
83 #include <process.h> // for getpid
84 #endif
85
86 #include <math.h>
87 #include <fcntl.h>
88 #include <stdio.h>
89 #include <string.h>
90 #include <stdlib.h>
91
92 #include "DNA_anim_types.h"
93 #include "DNA_armature_types.h"
94 #include "DNA_action_types.h"
95 #include "DNA_actuator_types.h"
96 #include "DNA_brush_types.h"
97 #include "DNA_camera_types.h"
98 #include "DNA_cloth_types.h"
99 #include "DNA_color_types.h"
100 #include "DNA_constraint_types.h"
101 #include "DNA_controller_types.h"
102 #include "DNA_curve_types.h"
103 #include "DNA_customdata_types.h"
104 #include "DNA_effect_types.h"
105 #include "DNA_genfile.h"
106 #include "DNA_group_types.h"
107 #include "DNA_gpencil_types.h"
108 #include "DNA_image_types.h"
109 #include "DNA_ipo_types.h"      // XXX depreceated - animsys
110 #include "DNA_fileglobal_types.h"
111 #include "DNA_key_types.h"
112 #include "DNA_lattice_types.h"
113 #include "DNA_listBase.h" /* for Listbase, the type of samples, ...*/
114 #include "DNA_lamp_types.h"
115 #include "DNA_meta_types.h"
116 #include "DNA_mesh_types.h"
117 #include "DNA_meshdata_types.h"
118 #include "DNA_material_types.h"
119 #include "DNA_modifier_types.h"
120 #include "DNA_nla_types.h"
121 #include "DNA_node_types.h"
122 #include "DNA_object_types.h"
123 #include "DNA_object_force.h"
124 #include "DNA_outliner_types.h"
125 #include "DNA_packedFile_types.h"
126 #include "DNA_particle_types.h"
127 #include "DNA_property_types.h"
128 #include "DNA_scene_types.h"
129 #include "DNA_sdna_types.h"
130 #include "DNA_sequence_types.h"
131 #include "DNA_sensor_types.h"
132 #include "DNA_space_types.h"
133 #include "DNA_screen_types.h"
134 #include "DNA_sound_types.h"
135 #include "DNA_texture_types.h"
136 #include "DNA_text_types.h"
137 #include "DNA_view3d_types.h"
138 #include "DNA_vfont_types.h"
139 #include "DNA_userdef_types.h"
140 #include "DNA_world_types.h"
141 #include "DNA_windowmanager_types.h"
142
143 #include "MEM_guardedalloc.h" // MEM_freeN
144 #include "BLI_blenlib.h"
145 #include "BLI_linklist.h"
146
147 #include "BKE_action.h"
148 #include "BKE_blender.h"
149 #include "BKE_cloth.h"
150 #include "BKE_curve.h"
151 #include "BKE_customdata.h"
152 #include "BKE_constraint.h"
153 #include "BKE_global.h" // for G
154 #include "BKE_library.h" // for  set_listbasepointers
155 #include "BKE_main.h"
156 #include "BKE_node.h"
157 #include "BKE_packedFile.h" // for packAll
158 #include "BKE_report.h"
159 #include "BKE_screen.h" // for waitcursor
160 #include "BKE_sequence.h"
161 #include "BKE_sound.h" /* ... and for samples */
162 #include "BKE_utildefines.h" // for defines
163 #include "BKE_modifier.h"
164 #include "BKE_idprop.h"
165 #include "BKE_fcurve.h"
166
167 #include "BLO_writefile.h"
168 #include "BLO_readfile.h"
169 #include "BLO_undofile.h"
170
171 #include "readfile.h"
172
173 #include <errno.h>
174
175 /* ********* my write, buffered writing with minimum size chunks ************ */
176
177 #define MYWRITE_BUFFER_SIZE     100000
178 #define MYWRITE_MAX_CHUNK       32768
179
180 typedef struct {
181         struct SDNA *sdna;
182
183         int file;
184         unsigned char *buf;
185         MemFile *compare, *current;
186         
187         int tot, count, error, memsize;
188 } WriteData;
189
190 static WriteData *writedata_new(int file)
191 {
192         WriteData *wd= MEM_callocN(sizeof(*wd), "writedata");
193
194                 /* XXX, see note about this in readfile.c, remove
195                  * once we have an xp lock - zr
196                  */
197
198         if (wd == NULL) return NULL;
199
200         wd->sdna= DNA_sdna_from_data(DNAstr, DNAlen, 0);
201
202         wd->file= file;
203
204         wd->buf= MEM_mallocN(MYWRITE_BUFFER_SIZE, "wd->buf");
205
206         return wd;
207 }
208
209 static void writedata_do_write(WriteData *wd, void *mem, int memlen)
210 {
211         if ((wd == NULL) || wd->error || (mem == NULL) || memlen < 1) return;
212         if (wd->error) return;
213
214         /* memory based save */
215         if(wd->current) {
216                 add_memfilechunk(NULL, wd->current, mem, memlen);
217         }
218         else {
219                 if (write(wd->file, mem, memlen) != memlen)
220                         wd->error= 1;
221                 
222         }
223 }
224
225 static void writedata_free(WriteData *wd)
226 {
227         DNA_sdna_free(wd->sdna);
228
229         MEM_freeN(wd->buf);
230         MEM_freeN(wd);
231 }
232
233 /***/
234
235 int mywfile;
236
237 /**
238  * Low level WRITE(2) wrapper that buffers data
239  * @param adr Pointer to new chunk of data
240  * @param len Length of new chunk of data
241  * @warning Talks to other functions with global parameters
242  */
243  
244 #define MYWRITE_FLUSH           NULL
245
246 static void mywrite( WriteData *wd, void *adr, int len)
247 {
248         if (wd->error) return;
249
250         /* flush helps compression for undo-save */
251         if(adr==MYWRITE_FLUSH) {
252                 if(wd->count) {
253                         writedata_do_write(wd, wd->buf, wd->count);
254                         wd->count= 0;
255                 }
256                 return;
257         }
258
259         wd->tot+= len;
260         
261         /* if we have a single big chunk, write existing data in
262          * buffer and write out big chunk in smaller pieces */
263         if(len>MYWRITE_MAX_CHUNK) {
264                 if(wd->count) {
265                         writedata_do_write(wd, wd->buf, wd->count);
266                         wd->count= 0;
267                 }
268
269                 do {
270                         int writelen= MIN2(len, MYWRITE_MAX_CHUNK);
271                         writedata_do_write(wd, adr, writelen);
272                         adr = (char*)adr + writelen;
273                         len -= writelen;
274                 } while(len > 0);
275
276                 return;
277         }
278
279         /* if data would overflow buffer, write out the buffer */
280         if(len+wd->count>MYWRITE_BUFFER_SIZE-1) {
281                 writedata_do_write(wd, wd->buf, wd->count);
282                 wd->count= 0;
283         }
284
285         /* append data at end of buffer */
286         memcpy(&wd->buf[wd->count], adr, len);
287         wd->count+= len;
288 }
289
290 /**
291  * BeGiN initializer for mywrite
292  * @param file File descriptor
293  * @param write_flags Write parameters
294  * @warning Talks to other functions with global parameters
295  */
296 static WriteData *bgnwrite(int file, MemFile *compare, MemFile *current, int write_flags)
297 {
298         WriteData *wd= writedata_new(file);
299
300         if (wd == NULL) return NULL;
301
302         wd->compare= compare;
303         wd->current= current;
304         /* this inits comparing */
305         add_memfilechunk(compare, NULL, NULL, 0);
306         
307         return wd;
308 }
309
310 /**
311  * END the mywrite wrapper
312  * @return 1 if write failed
313  * @return unknown global variable otherwise
314  * @warning Talks to other functions with global parameters
315  */
316 static int endwrite(WriteData *wd)
317 {
318         int err;
319
320         if (wd->count) {
321                 writedata_do_write(wd, wd->buf, wd->count);
322                 wd->count= 0;
323         }
324         
325         err= wd->error;
326         writedata_free(wd);
327
328         return err;
329 }
330
331 /* ********** WRITE FILE ****************** */
332
333 static void writestruct(WriteData *wd, int filecode, char *structname, int nr, void *adr)
334 {
335         BHead bh;
336         short *sp;
337
338         if(adr==NULL || nr==0) return;
339
340         /* init BHead */
341         bh.code= filecode;
342         bh.old= adr;
343         bh.nr= nr;
344
345         bh.SDNAnr= DNA_struct_find_nr(wd->sdna, structname);
346         if(bh.SDNAnr== -1) {
347                 printf("error: can't find SDNA code <%s>\n", structname);
348                 return;
349         }
350         sp= wd->sdna->structs[bh.SDNAnr];
351
352         bh.len= nr*wd->sdna->typelens[sp[0]];
353
354         if(bh.len==0) return;
355
356         mywrite(wd, &bh, sizeof(BHead));
357         mywrite(wd, adr, bh.len);
358 }
359
360 static void writedata(WriteData *wd, int filecode, int len, void *adr)  /* do not use for structs */
361 {
362         BHead bh;
363
364         if(adr==0) return;
365         if(len==0) return;
366
367         len+= 3;
368         len-= ( len % 4);
369
370         /* init BHead */
371         bh.code= filecode;
372         bh.old= adr;
373         bh.nr= 1;
374         bh.SDNAnr= 0;
375         bh.len= len;
376
377         mywrite(wd, &bh, sizeof(BHead));
378         if(len) mywrite(wd, adr, len);
379 }
380
381 /* *************** writing some direct data structs used in more code parts **************** */
382 /*These functions are used by blender's .blend system for file saving/loading.*/
383 void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd);
384 void IDP_WriteProperty(IDProperty *prop, void *wd);
385
386 static void IDP_WriteArray(IDProperty *prop, void *wd)
387 {
388         /*REMEMBER to set totalen to len in the linking code!!*/
389         if (prop->data.pointer) {
390                 writedata(wd, DATA, MEM_allocN_len(prop->data.pointer), prop->data.pointer);
391
392                 if(prop->subtype == IDP_GROUP) {
393                         IDProperty **array= prop->data.pointer;
394                         int a;
395
396                         for(a=0; a<prop->len; a++)
397                                 IDP_WriteProperty(array[a], wd);
398                 }
399         }
400 }
401
402 static void IDP_WriteIDPArray(IDProperty *prop, void *wd)
403 {
404         /*REMEMBER to set totalen to len in the linking code!!*/
405         if (prop->data.pointer) {
406                 IDProperty **array = prop->data.pointer;
407                 int a;
408
409                 writedata(wd, DATA, MEM_allocN_len(prop->data.pointer), prop->data.pointer);
410
411                 for(a=0; a<prop->len; a++)
412                         IDP_WriteProperty(array[a], wd);
413         }
414 }
415
416 static void IDP_WriteString(IDProperty *prop, void *wd)
417 {
418         /*REMEMBER to set totalen to len in the linking code!!*/
419         writedata(wd, DATA, prop->len+1, prop->data.pointer);
420 }
421
422 static void IDP_WriteGroup(IDProperty *prop, void *wd)
423 {
424         IDProperty *loop;
425
426         for (loop=prop->data.group.first; loop; loop=loop->next) {
427                 IDP_WriteProperty(loop, wd);
428         }
429 }
430
431 /* Functions to read/write ID Properties */
432 void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd)
433 {
434         switch (prop->type) {
435                 case IDP_GROUP:
436                         IDP_WriteGroup(prop, wd);
437                         break;
438                 case IDP_STRING:
439                         IDP_WriteString(prop, wd);
440                         break;
441                 case IDP_ARRAY:
442                         IDP_WriteArray(prop, wd);
443                         break;
444                 case IDP_IDPARRAY:
445                         IDP_WriteIDPArray(prop, wd);
446                         break;
447         }
448 }
449
450 void IDP_WriteProperty(IDProperty *prop, void *wd)
451 {
452         writestruct(wd, DATA, "IDProperty", 1, prop);
453         IDP_WriteProperty_OnlyData(prop, wd);
454 }
455
456 static void write_curvemapping(WriteData *wd, CurveMapping *cumap)
457 {
458         int a;
459         
460         writestruct(wd, DATA, "CurveMapping", 1, cumap);
461         for(a=0; a<CM_TOT; a++)
462                 writestruct(wd, DATA, "CurveMapPoint", cumap->cm[a].totpoint, cumap->cm[a].curve);
463 }
464
465 /* this is only direct data, tree itself should have been written */
466 static void write_nodetree(WriteData *wd, bNodeTree *ntree)
467 {
468         bNode *node;
469         bNodeSocket *sock;
470         bNodeLink *link;
471         
472         /* for link_list() speed, we write per list */
473         
474         for(node= ntree->nodes.first; node; node= node->next)
475                 writestruct(wd, DATA, "bNode", 1, node);
476
477         for(node= ntree->nodes.first; node; node= node->next) {
478                 if(node->storage && node->type!=NODE_DYNAMIC) {
479                         /* could be handlerized at some point, now only 1 exception still */
480                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
481                                 write_curvemapping(wd, node->storage);
482                         else if(ntree->type==NTREE_COMPOSIT && (node->type==CMP_NODE_TIME || node->type==CMP_NODE_CURVE_VEC || node->type==CMP_NODE_CURVE_RGB))
483                                 write_curvemapping(wd, node->storage);
484                         else if(ntree->type==NTREE_TEXTURE && (node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME) )
485                                 write_curvemapping(wd, node->storage);
486                         else 
487                                 writestruct(wd, DATA, node->typeinfo->storagename, 1, node->storage);
488                 }
489                 for(sock= node->inputs.first; sock; sock= sock->next)
490                         writestruct(wd, DATA, "bNodeSocket", 1, sock);
491                 for(sock= node->outputs.first; sock; sock= sock->next)
492                         writestruct(wd, DATA, "bNodeSocket", 1, sock);
493         }
494         
495         for(link= ntree->links.first; link; link= link->next)
496                 writestruct(wd, DATA, "bNodeLink", 1, link);
497 }
498
499 static void write_scriptlink(WriteData *wd, ScriptLink *slink)
500 {
501         writedata(wd, DATA, sizeof(void *)*slink->totscript, slink->scripts);
502         writedata(wd, DATA, sizeof(short)*slink->totscript, slink->flag);
503 }
504
505 static void current_screen_compat(Main *mainvar, bScreen **screen)
506 {
507         wmWindowManager *wm;
508         wmWindow *window;
509
510         /* find a global current screen in the first open window, to have
511          * a reasonable default for reading in older versions */
512         wm= mainvar->wm.first;
513         window= (wm)? wm->windows.first: NULL;
514         *screen= (window)? window->screen: NULL;
515 }
516
517 static void write_renderinfo(WriteData *wd, Main *mainvar)              /* for renderdeamon */
518 {
519         bScreen *curscreen;
520         Scene *sce;
521         int data[8];
522
523         /* XXX in future, handle multiple windows with multiple screnes? */
524         current_screen_compat(mainvar, &curscreen);
525
526         for(sce= mainvar->scene.first; sce; sce= sce->id.next) {
527                 if(sce->id.lib==NULL  && ( sce==curscreen->scene || (sce->r.scemode & R_BG_RENDER)) ) {
528                         data[0]= sce->r.sfra;
529                         data[1]= sce->r.efra;
530
531                         memset(data+2, 0, sizeof(int)*6);
532                         strncpy((char *)(data+2), sce->id.name+2, 21);
533
534                         writedata(wd, REND, 32, data);
535                 }
536         }
537 }
538
539 static void write_userdef(WriteData *wd)
540 {
541         bTheme *btheme;
542
543         writestruct(wd, USER, "UserDef", 1, &U);
544
545         btheme= U.themes.first;
546         while(btheme) {
547                 writestruct(wd, DATA, "bTheme", 1, btheme);
548                 btheme= btheme->next;
549         }
550 }
551
552 /* TODO: replace *cache with *cachelist once it's coded */
553 #define PTCACHE_WRITE_PSYS      0
554 static void write_pointcaches(WriteData *wd, PointCache *cache, int type)
555 {
556         writestruct(wd, DATA, "PointCache", 1, cache);
557
558         if((cache->flag & PTCACHE_DISK_CACHE)==0) {
559                 PTCacheMem *pm = cache->mem_cache.first;
560
561                 for(; pm; pm=pm->next) {
562                         writestruct(wd, DATA, "PTCacheMem", 1, pm);
563                         if(type==PTCACHE_WRITE_PSYS)
564                                 writestruct(wd, DATA, "ParticleKey", pm->totpoint, pm->data);
565                 }
566         }
567 }
568 static void write_particlesettings(WriteData *wd, ListBase *idbase)
569 {
570         ParticleSettings *part;
571
572         part= idbase->first;
573         while(part) {
574                 if(part->id.us>0 || wd->current) {
575                         /* write LibData */
576                         writestruct(wd, ID_PA, "ParticleSettings", 1, part);
577                         if (part->id.properties) IDP_WriteProperty(part->id.properties, wd);
578                         writestruct(wd, DATA, "PartDeflect", 1, part->pd);
579                         writestruct(wd, DATA, "PartDeflect", 1, part->pd2);
580                 }
581                 part= part->id.next;
582         }
583 }
584 static void write_particlesystems(WriteData *wd, ListBase *particles)
585 {
586         ParticleSystem *psys= particles->first;
587         int a;
588
589         for(; psys; psys=psys->next) {
590                 writestruct(wd, DATA, "ParticleSystem", 1, psys);
591
592                 if(psys->particles) {
593                         writestruct(wd, DATA, "ParticleData", psys->totpart ,psys->particles);
594
595                         if(psys->particles->hair) {
596                                 ParticleData *pa = psys->particles;
597
598                                 for(a=0; a<psys->totpart; a++, pa++)
599                                         writestruct(wd, DATA, "HairKey", pa->totkey, pa->hair);
600                         }
601                 }
602                 if(psys->child) writestruct(wd, DATA, "ChildParticle", psys->totchild ,psys->child);
603                 writestruct(wd, DATA, "SoftBody", 1, psys->soft);
604                 if(psys->soft) write_pointcaches(wd, psys->soft->pointcache, PTCACHE_WRITE_PSYS);
605                 write_pointcaches(wd, psys->pointcache, PTCACHE_WRITE_PSYS);
606         }
607 }
608
609 static void write_properties(WriteData *wd, ListBase *lb)
610 {
611         bProperty *prop;
612
613         prop= lb->first;
614         while(prop) {
615                 writestruct(wd, DATA, "bProperty", 1, prop);
616
617                 if(prop->poin && prop->poin != &prop->data)
618                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
619
620                 prop= prop->next;
621         }
622 }
623
624 static void write_sensors(WriteData *wd, ListBase *lb)
625 {
626         bSensor *sens;
627
628         sens= lb->first;
629         while(sens) {
630                 writestruct(wd, DATA, "bSensor", 1, sens);
631
632                 writedata(wd, DATA, sizeof(void *)*sens->totlinks, sens->links);
633
634                 switch(sens->type) {
635                 case SENS_NEAR:
636                         writestruct(wd, DATA, "bNearSensor", 1, sens->data);
637                         break;
638                 case SENS_MOUSE:
639                         writestruct(wd, DATA, "bMouseSensor", 1, sens->data);
640                         break;
641                 case SENS_TOUCH:
642                         writestruct(wd, DATA, "bTouchSensor", 1, sens->data);
643                         break;
644                 case SENS_KEYBOARD:
645                         writestruct(wd, DATA, "bKeyboardSensor", 1, sens->data);
646                         break;
647                 case SENS_PROPERTY:
648                         writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
649                         break;
650                 case SENS_ACTUATOR:
651                         writestruct(wd, DATA, "bActuatorSensor", 1, sens->data);
652                         break;
653                 case SENS_DELAY:
654                         writestruct(wd, DATA, "bDelaySensor", 1, sens->data);
655                         break;
656                 case SENS_COLLISION:
657                         writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
658                         break;
659                 case SENS_RADAR:
660                         writestruct(wd, DATA, "bRadarSensor", 1, sens->data);
661                         break;
662                 case SENS_RANDOM:
663                         writestruct(wd, DATA, "bRandomSensor", 1, sens->data);
664                         break;
665                 case SENS_RAY:
666                         writestruct(wd, DATA, "bRaySensor", 1, sens->data);
667                         break;
668                 case SENS_MESSAGE:
669                         writestruct(wd, DATA, "bMessageSensor", 1, sens->data);
670                         break;
671                 case SENS_JOYSTICK:
672                         writestruct(wd, DATA, "bJoystickSensor", 1, sens->data);
673                         break;
674                 default:
675                         ; /* error: don't know how to write this file */
676                 }
677
678                 sens= sens->next;
679         }
680 }
681
682 static void write_controllers(WriteData *wd, ListBase *lb)
683 {
684         bController *cont;
685
686         cont= lb->first;
687         while(cont) {
688                 writestruct(wd, DATA, "bController", 1, cont);
689
690                 writedata(wd, DATA, sizeof(void *)*cont->totlinks, cont->links);
691
692                 switch(cont->type) {
693                 case CONT_EXPRESSION:
694                         writestruct(wd, DATA, "bExpressionCont", 1, cont->data);
695                         break;
696                 case CONT_PYTHON:
697                         writestruct(wd, DATA, "bPythonCont", 1, cont->data);
698                         break;
699                 default:
700                         ; /* error: don't know how to write this file */
701                 }
702
703                 cont= cont->next;
704         }
705 }
706
707 static void write_actuators(WriteData *wd, ListBase *lb)
708 {
709         bActuator *act;
710
711         act= lb->first;
712         while(act) {
713                 writestruct(wd, DATA, "bActuator", 1, act);
714
715                 switch(act->type) {
716                 case ACT_ACTION:
717                 case ACT_SHAPEACTION:
718                         writestruct(wd, DATA, "bActionActuator", 1, act->data);
719                         break;
720                 case ACT_SOUND:
721                         writestruct(wd, DATA, "bSoundActuator", 1, act->data);
722                         break;
723                 case ACT_CD:
724                         writestruct(wd, DATA, "bCDActuator", 1, act->data);
725                         break;
726                 case ACT_OBJECT:
727                         writestruct(wd, DATA, "bObjectActuator", 1, act->data);
728                         break;
729                 case ACT_IPO:
730                         writestruct(wd, DATA, "bIpoActuator", 1, act->data);
731                         break;
732                 case ACT_PROPERTY:
733                         writestruct(wd, DATA, "bPropertyActuator", 1, act->data);
734                         break;
735                 case ACT_CAMERA:
736                         writestruct(wd, DATA, "bCameraActuator", 1, act->data);
737                         break;
738                 case ACT_CONSTRAINT:
739                         writestruct(wd, DATA, "bConstraintActuator", 1, act->data);
740                         break;
741                 case ACT_EDIT_OBJECT:
742                         writestruct(wd, DATA, "bEditObjectActuator", 1, act->data);
743                         break;
744                 case ACT_SCENE:
745                         writestruct(wd, DATA, "bSceneActuator", 1, act->data);
746                         break;
747                 case ACT_GROUP:
748                         writestruct(wd, DATA, "bGroupActuator", 1, act->data);
749                         break;
750                 case ACT_RANDOM:
751                         writestruct(wd, DATA, "bRandomActuator", 1, act->data);
752                         break;
753                 case ACT_MESSAGE:
754                         writestruct(wd, DATA, "bMessageActuator", 1, act->data);
755                         break;
756                 case ACT_GAME:
757                         writestruct(wd, DATA, "bGameActuator", 1, act->data);
758                         break;
759                 case ACT_VISIBILITY:
760                         writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
761                         break;
762                 case ACT_2DFILTER:
763                         writestruct(wd, DATA, "bTwoDFilterActuator", 1, act->data);
764                         break;
765                 case ACT_PARENT:
766                         writestruct(wd, DATA, "bParentActuator", 1, act->data);
767                         break;
768                 case ACT_STATE:
769                         writestruct(wd, DATA, "bStateActuator", 1, act->data);
770                         break;
771                 default:
772                         ; /* error: don't know how to write this file */
773                 }
774
775                 act= act->next;
776         }
777 }
778
779 static void write_fcurves(WriteData *wd, ListBase *fcurves)
780 {
781         FCurve *fcu;
782         FModifier *fcm;
783         
784         for (fcu=fcurves->first; fcu; fcu=fcu->next) {
785                 /* F-Curve */
786                 writestruct(wd, DATA, "FCurve", 1, fcu);
787                 
788                 /* curve data */
789                 if (fcu->bezt)          
790                         writestruct(wd, DATA, "BezTriple", fcu->totvert, fcu->bezt);
791                 if (fcu->fpt)
792                         writestruct(wd, DATA, "FPoint", fcu->totvert, fcu->fpt);
793                         
794                 if (fcu->rna_path)
795                         writedata(wd, DATA, strlen(fcu->rna_path)+1, fcu->rna_path);
796                 
797                 /* driver data */
798                 if (fcu->driver) {
799                         ChannelDriver *driver= fcu->driver;
800                         DriverTarget *dtar;
801                         
802                         writestruct(wd, DATA, "ChannelDriver", 1, driver);
803                         
804                         /* targets */
805                         for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
806                                 writestruct(wd, DATA, "DriverTarget", 1, dtar);
807                                 
808                                 if (dtar->rna_path)
809                                         writedata(wd, DATA, strlen(dtar->rna_path)+1, dtar->rna_path);
810                         }
811                 }
812                 
813                 /* Modifiers */
814                 for (fcm= fcu->modifiers.first; fcm; fcm= fcm->next) {
815                         FModifierTypeInfo *fmi= fmodifier_get_typeinfo(fcm);
816                         
817                         /* Write the specific data */
818                         if (fmi && fcm->data) {
819                                 /* firstly, just write the plain fmi->data struct */
820                                 writestruct(wd, DATA, fmi->structName, 1, fcm->data);
821                                 
822                                 /* do any modifier specific stuff */
823                                 switch (fcm->type) {
824                                         case FMODIFIER_TYPE_GENERATOR:
825                                         {
826                                                 FMod_Generator *data= (FMod_Generator *)fcm->data;
827                                                 
828                                                 /* write coefficients array */
829                                                 if (data->coefficients)
830                                                         writedata(wd, DATA, sizeof(float)*(data->arraysize), data->coefficients);
831                                         }
832                                                 break;
833                                         case FMODIFIER_TYPE_ENVELOPE:
834                                         {
835                                                 FMod_Envelope *data= (FMod_Envelope *)fcm->data;
836                                                 
837                                                 /* write envelope data */
838                                                 if (data->data)
839                                                         writedata(wd, DATA, sizeof(FCM_EnvelopeData)*(data->totvert), data->data);
840                                         }
841                                                 break;
842                                         case FMODIFIER_TYPE_PYTHON:
843                                         {
844                                                 FMod_Python *data = (FMod_Python *)fcm->data;
845                                                 
846                                                 /* Write ID Properties -- and copy this comment EXACTLY for easy finding
847                                                  of library blocks that implement this.*/
848                                                 IDP_WriteProperty(data->prop, wd);
849                                         }
850                                                 break;
851                                 }
852                         }
853                         
854                         /* Write the modifier */
855                         writestruct(wd, DATA, "FModifier", 1, fcm);
856                 }
857         }
858 }
859
860 static void write_actions(WriteData *wd, ListBase *idbase)
861 {
862         bAction *act;
863         bActionGroup *grp;
864         TimeMarker *marker;
865         
866         for(act=idbase->first; act; act= act->id.next) {
867                 if (act->id.us>0 || wd->current) {
868                         writestruct(wd, ID_AC, "bAction", 1, act);
869                         if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
870                         
871                         write_fcurves(wd, &act->curves);
872                         
873                         for (grp=act->groups.first; grp; grp=grp->next) {
874                                 writestruct(wd, DATA, "bActionGroup", 1, grp);
875                         }
876                         
877                         for (marker=act->markers.first; marker; marker=marker->next) {
878                                 writestruct(wd, DATA, "TimeMarker", 1, marker);
879                         }
880                 }
881         }
882         
883         /* flush helps the compression for undo-save */
884         mywrite(wd, MYWRITE_FLUSH, 0);
885 }
886
887 static void write_keyingsets(WriteData *wd, ListBase *list)
888 {
889         KeyingSet *ks;
890         KS_Path *ksp;
891         
892         for (ks= list->first; ks; ks= ks->next) {
893                 /* KeyingSet */
894                 writestruct(wd, DATA, "KeyingSet", 1, ks);
895                 
896                 /* Paths */
897                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
898                         /* Path */
899                         writestruct(wd, DATA, "KS_Path", 1, ksp);
900                         
901                         if (ksp->rna_path)
902                                 writedata(wd, DATA, strlen(ksp->rna_path)+1, ksp->rna_path);
903                 }
904         }
905 }
906
907 static void write_animdata(WriteData *wd, AnimData *adt)
908 {
909         AnimOverride *aor;
910         
911         /* firstly, just write the AnimData block */
912         writestruct(wd, DATA, "AnimData", 1, adt);
913         
914         /* write drivers */
915         write_fcurves(wd, &adt->drivers);
916         
917         /* write overrides */
918         for (aor= adt->overrides.first; aor; aor= aor->next) {
919                 /* overrides consist of base data + rna_path */
920                 writestruct(wd, DATA, "AnimOverride", 1, aor);
921                 writedata(wd, DATA, strlen(aor->rna_path)+1, aor->rna_path);
922         }
923         
924         /* write NLA data */
925         // XXX todo...
926 }
927
928 static void write_constraints(WriteData *wd, ListBase *conlist)
929 {
930         bConstraint *con;
931
932         for (con=conlist->first; con; con=con->next) {
933                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
934                 
935                 /* Write the specific data */
936                 if (cti && con->data) {
937                         /* firstly, just write the plain con->data struct */
938                         writestruct(wd, DATA, cti->structName, 1, con->data);
939                         
940                         /* do any constraint specific stuff */
941                         switch (con->type) {
942                                 case CONSTRAINT_TYPE_PYTHON:
943                                 {
944                                         bPythonConstraint *data = (bPythonConstraint *)con->data;
945                                         bConstraintTarget *ct;
946                                         
947                                         /* write targets */
948                                         for (ct= data->targets.first; ct; ct= ct->next)
949                                                 writestruct(wd, DATA, "bConstraintTarget", 1, ct);
950                                         
951                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
952                                          of library blocks that implement this.*/
953                                         IDP_WriteProperty(data->prop, wd);
954                                 }
955                                 break;
956                         }
957                 }
958                 
959                 /* Write the constraint */
960                 writestruct(wd, DATA, "bConstraint", 1, con);
961         }
962 }
963
964 static void write_pose(WriteData *wd, bPose *pose)
965 {
966         bPoseChannel *chan;
967         bActionGroup *grp;
968
969         /* Write each channel */
970         if (!pose)
971                 return;
972
973         /* Write channels */
974         for (chan=pose->chanbase.first; chan; chan=chan->next) {
975                 /* Write ID Properties -- and copy this comment EXACTLY for easy finding
976                  of library blocks that implement this.*/
977                 if (chan->prop)
978                         IDP_WriteProperty(chan->prop, wd);
979                 
980                 write_constraints(wd, &chan->constraints);
981                 
982                 /* prevent crashes with autosave, when a bone duplicated in editmode has not yet been assigned to its posechannel */
983                 if (chan->bone) 
984                         chan->selectflag= chan->bone->flag & (BONE_SELECTED|BONE_ACTIVE); /* gets restored on read, for library armatures */
985                 
986                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
987         }
988         
989         /* Write groups */
990         for (grp=pose->agroups.first; grp; grp=grp->next) 
991                 writestruct(wd, DATA, "bActionGroup", 1, grp);
992
993         /* Write this pose */
994         writestruct(wd, DATA, "bPose", 1, pose);
995 }
996
997 static void write_defgroups(WriteData *wd, ListBase *defbase)
998 {
999         bDeformGroup    *defgroup;
1000
1001         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
1002                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
1003 }
1004
1005 static void write_modifiers(WriteData *wd, ListBase *modbase, int write_undo)
1006 {
1007         ModifierData *md;
1008
1009         if (modbase == NULL) return;
1010         for (md=modbase->first; md; md= md->next) {
1011                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1012                 if (mti == NULL) return;
1013                 
1014                 writestruct(wd, DATA, mti->structName, 1, md);
1015                         
1016                 if (md->type==eModifierType_Hook) {
1017                         HookModifierData *hmd = (HookModifierData*) md;
1018                         
1019                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
1020                 }
1021                 else if(md->type==eModifierType_Cloth) {
1022                         ClothModifierData *clmd = (ClothModifierData*) md;
1023                         
1024                         writestruct(wd, DATA, "ClothSimSettings", 1, clmd->sim_parms);
1025                         writestruct(wd, DATA, "ClothCollSettings", 1, clmd->coll_parms);
1026                         writestruct(wd, DATA, "PointCache", 1, clmd->point_cache);
1027                 } 
1028                 else if(md->type==eModifierType_Fluidsim) {
1029                         FluidsimModifierData *fluidmd = (FluidsimModifierData*) md;
1030                         
1031                         writestruct(wd, DATA, "FluidsimSettings", 1, fluidmd->fss);
1032                 } 
1033                 else if (md->type==eModifierType_Collision) {
1034                         
1035                         /*
1036                         CollisionModifierData *collmd = (CollisionModifierData*) md;
1037                         // TODO: CollisionModifier should use pointcache 
1038                         // + have proper reset events before enabling this
1039                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->x);
1040                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->xnew);
1041                         writestruct(wd, DATA, "MFace", collmd->numfaces, collmd->mfaces);
1042                         */
1043                 }
1044                 else if (md->type==eModifierType_MeshDeform) {
1045                         MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
1046                         int size = mmd->dyngridsize;
1047
1048                         writedata(wd, DATA, sizeof(float)*mmd->totvert*mmd->totcagevert,
1049                                 mmd->bindweights);
1050                         writedata(wd, DATA, sizeof(float)*3*mmd->totcagevert,
1051                                 mmd->bindcos);
1052                         writestruct(wd, DATA, "MDefCell", size*size*size, mmd->dyngrid);
1053                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->dyninfluences);
1054                         writedata(wd, DATA, sizeof(int)*mmd->totvert, mmd->dynverts);
1055                 }
1056                 else if (md->type==eModifierType_Multires) {
1057                         MultiresModifierData *mmd = (MultiresModifierData*) md;
1058
1059                         if(mmd->undo_verts && write_undo)
1060                                 writestruct(wd, DATA, "MVert", mmd->undo_verts_tot, mmd->undo_verts);
1061                 }
1062         }
1063 }
1064
1065 static void write_objects(WriteData *wd, ListBase *idbase, int write_undo)
1066 {
1067         Object *ob;
1068         
1069         ob= idbase->first;
1070         while(ob) {
1071                 if(ob->id.us>0 || wd->current) {
1072                         /* write LibData */
1073                         writestruct(wd, ID_OB, "Object", 1, ob);
1074                         
1075                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1076                           of library blocks that implement this.*/
1077                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
1078                         
1079                         if (ob->adt) write_animdata(wd, ob->adt);
1080                         
1081                         /* direct data */
1082                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
1083                         /* write_effects(wd, &ob->effect); */ /* not used anymore */
1084                         write_properties(wd, &ob->prop);
1085                         write_sensors(wd, &ob->sensors);
1086                         write_controllers(wd, &ob->controllers);
1087                         write_actuators(wd, &ob->actuators);
1088                         write_scriptlink(wd, &ob->scriptlink);
1089                         write_pose(wd, ob->pose);
1090                         write_defgroups(wd, &ob->defbase);
1091                         write_constraints(wd, &ob->constraints);
1092                         
1093                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
1094                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
1095                         if(ob->soft) writestruct(wd, DATA, "PointCache", 1, ob->soft->pointcache);
1096                         writestruct(wd, DATA, "BulletSoftBody", 1, ob->bsoft);
1097                         
1098                         write_particlesystems(wd, &ob->particlesystem);
1099                         write_modifiers(wd, &ob->modifiers, write_undo);
1100                 }
1101                 ob= ob->id.next;
1102         }
1103
1104         /* flush helps the compression for undo-save */
1105         mywrite(wd, MYWRITE_FLUSH, 0);
1106 }
1107
1108
1109 static void write_vfonts(WriteData *wd, ListBase *idbase)
1110 {
1111         VFont *vf;
1112         PackedFile * pf;
1113
1114         vf= idbase->first;
1115         while(vf) {
1116                 if(vf->id.us>0 || wd->current) {
1117                         /* write LibData */
1118                         writestruct(wd, ID_VF, "VFont", 1, vf);
1119                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
1120
1121                         /* direct data */
1122
1123                         if (vf->packedfile) {
1124                                 pf = vf->packedfile;
1125                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1126                                 writedata(wd, DATA, pf->size, pf->data);
1127                         }
1128                 }
1129
1130                 vf= vf->id.next;
1131         }
1132 }
1133
1134
1135 static void write_keys(WriteData *wd, ListBase *idbase)
1136 {
1137         Key *key;
1138         KeyBlock *kb;
1139
1140         key= idbase->first;
1141         while(key) {
1142                 if(key->id.us>0 || wd->current) {
1143                         /* write LibData */
1144                         writestruct(wd, ID_KE, "Key", 1, key);
1145                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
1146                         
1147                         if (key->adt) write_animdata(wd, key->adt);
1148                         
1149                         /* direct data */
1150                         kb= key->block.first;
1151                         while(kb) {
1152                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
1153                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
1154                                 kb= kb->next;
1155                         }
1156                 }
1157
1158                 key= key->id.next;
1159         }
1160         /* flush helps the compression for undo-save */
1161         mywrite(wd, MYWRITE_FLUSH, 0);
1162 }
1163
1164 static void write_cameras(WriteData *wd, ListBase *idbase)
1165 {
1166         Camera *cam;
1167
1168         cam= idbase->first;
1169         while(cam) {
1170                 if(cam->id.us>0 || wd->current) {
1171                         /* write LibData */
1172                         writestruct(wd, ID_CA, "Camera", 1, cam);
1173                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
1174                         
1175                         if (cam->adt) write_animdata(wd, cam->adt);
1176                         
1177                         /* direct data */
1178                         write_scriptlink(wd, &cam->scriptlink);
1179                 }
1180
1181                 cam= cam->id.next;
1182         }
1183 }
1184
1185 static void write_mballs(WriteData *wd, ListBase *idbase)
1186 {
1187         MetaBall *mb;
1188         MetaElem *ml;
1189
1190         mb= idbase->first;
1191         while(mb) {
1192                 if(mb->id.us>0 || wd->current) {
1193                         /* write LibData */
1194                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
1195                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
1196
1197                         /* direct data */
1198                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
1199
1200                         ml= mb->elems.first;
1201                         while(ml) {
1202                                 writestruct(wd, DATA, "MetaElem", 1, ml);
1203                                 ml= ml->next;
1204                         }
1205                 }
1206                 mb= mb->id.next;
1207         }
1208 }
1209
1210 static int amount_of_chars(char *str)
1211 {
1212         // Since the data is saved as UTF-8 to the cu->str
1213         // The cu->len is not same as the strlen(cu->str)
1214         return strlen(str);
1215 }
1216
1217 static void write_curves(WriteData *wd, ListBase *idbase)
1218 {
1219         Curve *cu;
1220         Nurb *nu;
1221
1222         cu= idbase->first;
1223         while(cu) {
1224                 if(cu->id.us>0 || wd->current) {
1225                         /* write LibData */
1226                         writestruct(wd, ID_CU, "Curve", 1, cu);
1227                         
1228                         /* direct data */
1229                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
1230                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
1231                         if (cu->adt) write_animdata(wd, cu->adt);
1232                         
1233                         if(cu->vfont) {
1234                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1235                                 writestruct(wd, DATA, "CharInfo", cu->len, cu->strinfo);
1236                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);                           
1237                         }
1238                         else {
1239                                 /* is also the order of reading */
1240                                 nu= cu->nurb.first;
1241                                 while(nu) {
1242                                         writestruct(wd, DATA, "Nurb", 1, nu);
1243                                         nu= nu->next;
1244                                 }
1245                                 nu= cu->nurb.first;
1246                                 while(nu) {
1247                                         if( (nu->type & 7)==CU_BEZIER)
1248                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1249                                         else {
1250                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1251                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1252                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1253                                         }
1254                                         nu= nu->next;
1255                                 }
1256                         }
1257                 }
1258                 cu= cu->id.next;
1259         }
1260
1261         /* flush helps the compression for undo-save */
1262         mywrite(wd, MYWRITE_FLUSH, 0);
1263 }
1264
1265 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1266 {
1267         if (dvlist) {
1268                 int i;
1269                 
1270                 /* Write the dvert list */
1271                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1272                 
1273                 /* Write deformation data for each dvert */
1274                 for (i=0; i<count; i++) {
1275                         if (dvlist[i].dw)
1276                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1277                 }
1278         }
1279 }
1280
1281 static void write_mdisps(WriteData *wd, int count, MDisps *mdlist)
1282 {
1283         if(mdlist) {
1284                 int i;
1285                 
1286                 writestruct(wd, DATA, "MDisps", count, mdlist);
1287                 for(i = 0; i < count; ++i) {
1288                         if(mdlist[i].disps)
1289                                 writedata(wd, DATA, sizeof(float)*3*mdlist[i].totdisp, mdlist[i].disps);
1290                 }
1291         }
1292 }
1293
1294 static void write_customdata(WriteData *wd, int count, CustomData *data, int partial_type, int partial_count)
1295 {
1296         int i;
1297
1298         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1299
1300         for (i=0; i<data->totlayer; i++) {
1301                 CustomDataLayer *layer= &data->layers[i];
1302                 char *structname;
1303                 int structnum, datasize;
1304
1305                 if (layer->type == CD_MDEFORMVERT) {
1306                         /* layer types that allocate own memory need special handling */
1307                         write_dverts(wd, count, layer->data);
1308                 }
1309                 else if (layer->type == CD_MDISPS) {
1310                         write_mdisps(wd, count, layer->data);
1311                 }
1312                 else {
1313                         CustomData_file_write_info(layer->type, &structname, &structnum);
1314                         if (structnum) {
1315                                 /* when using partial visibility, the MEdge and MFace layers
1316                                    are smaller than the original, so their type and count is
1317                                    passed to make this work */
1318                                 if (layer->type != partial_type) datasize= structnum*count;
1319                                 else datasize= structnum*partial_count;
1320
1321                                 writestruct(wd, DATA, structname, datasize, layer->data);
1322                         }
1323                         else
1324                                 printf("error: this CustomDataLayer must not be written to file\n");
1325                 }
1326         }
1327 }
1328
1329 static void write_meshs(WriteData *wd, ListBase *idbase)
1330 {
1331         Mesh *mesh;
1332
1333         mesh= idbase->first;
1334         while(mesh) {
1335                 if(mesh->id.us>0 || wd->current) {
1336                         /* write LibData */
1337                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
1338
1339                         /* direct data */
1340                         if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1341
1342                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1343
1344                         if(mesh->pv) {
1345                                 write_customdata(wd, mesh->pv->totvert, &mesh->vdata, -1, 0);
1346                                 write_customdata(wd, mesh->pv->totedge, &mesh->edata,
1347                                         CD_MEDGE, mesh->totedge);
1348                                 write_customdata(wd, mesh->pv->totface, &mesh->fdata,
1349                                         CD_MFACE, mesh->totface);
1350                         }
1351                         else {
1352                                 write_customdata(wd, mesh->totvert, &mesh->vdata, -1, 0);
1353                                 write_customdata(wd, mesh->totedge, &mesh->edata, -1, 0);
1354                                 write_customdata(wd, mesh->totface, &mesh->fdata, -1, 0);
1355                         }
1356
1357                         /* PMV data */
1358                         if(mesh->pv) {
1359                                 writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
1360                                 writedata(wd, DATA, sizeof(unsigned int)*mesh->pv->totvert, mesh->pv->vert_map);
1361                                 writedata(wd, DATA, sizeof(int)*mesh->pv->totedge, mesh->pv->edge_map);
1362                                 writestruct(wd, DATA, "MFace", mesh->pv->totface, mesh->pv->old_faces);
1363                                 writestruct(wd, DATA, "MEdge", mesh->pv->totedge, mesh->pv->old_edges);
1364                         }
1365                 }
1366                 mesh= mesh->id.next;
1367         }
1368 }
1369
1370 static void write_lattices(WriteData *wd, ListBase *idbase)
1371 {
1372         Lattice *lt;
1373         
1374         lt= idbase->first;
1375         while(lt) {
1376                 if(lt->id.us>0 || wd->current) {
1377                         /* write LibData */
1378                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1379                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1380
1381                         /* direct data */
1382                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1383                         
1384                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1385                         
1386                 }
1387                 lt= lt->id.next;
1388         }
1389 }
1390
1391 static void write_previews(WriteData *wd, PreviewImage *prv)
1392 {
1393         if (prv) {
1394                 short w = prv->w[1];
1395                 short h = prv->h[1];
1396                 unsigned int *rect = prv->rect[1];
1397                 /* don't write out large previews if not requested */
1398                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1399                         prv->w[1] = 0;
1400                         prv->h[1] = 0;
1401                         prv->rect[1] = NULL;
1402                 }
1403                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1404                 if (prv->rect[0]) writedata(wd, DATA, prv->w[0]*prv->h[0]*sizeof(unsigned int), prv->rect[0]);
1405                 if (prv->rect[1]) writedata(wd, DATA, prv->w[1]*prv->h[1]*sizeof(unsigned int), prv->rect[1]);
1406
1407                 /* restore preview, we still want to keep it in memory even if not saved to file */
1408                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1409                         prv->w[1] = w;
1410                         prv->h[1] = h;
1411                         prv->rect[1] = rect;
1412                 }
1413         }
1414 }
1415
1416 static void write_images(WriteData *wd, ListBase *idbase)
1417 {
1418         Image *ima;
1419         PackedFile * pf;
1420
1421
1422         ima= idbase->first;
1423         while(ima) {
1424                 if(ima->id.us>0 || wd->current) {
1425                         /* write LibData */
1426                         writestruct(wd, ID_IM, "Image", 1, ima);
1427                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1428
1429                         if (ima->packedfile) {
1430                                 pf = ima->packedfile;
1431                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1432                                 writedata(wd, DATA, pf->size, pf->data);
1433                         }
1434
1435                         write_previews(wd, ima->preview);
1436
1437                         }
1438                 ima= ima->id.next;
1439         }
1440         /* flush helps the compression for undo-save */
1441         mywrite(wd, MYWRITE_FLUSH, 0);
1442 }
1443
1444 static void write_textures(WriteData *wd, ListBase *idbase)
1445 {
1446         Tex *tex;
1447
1448         tex= idbase->first;
1449         while(tex) {
1450                 if(tex->id.us>0 || wd->current) {
1451                         /* write LibData */
1452                         writestruct(wd, ID_TE, "Tex", 1, tex);
1453                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1454
1455                         if (tex->adt) write_animdata(wd, tex->adt);
1456
1457                         /* direct data */
1458                         if(tex->type == TEX_PLUGIN && tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1459                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1460                         if(tex->type == TEX_ENVMAP && tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1461                         
1462                         /* nodetree is integral part of texture, no libdata */
1463                         if(tex->nodetree) {
1464                                 writestruct(wd, DATA, "bNodeTree", 1, tex->nodetree);
1465                                 write_nodetree(wd, tex->nodetree);
1466                         }
1467                         
1468                         write_previews(wd, tex->preview);
1469                 }
1470                 tex= tex->id.next;
1471         }
1472
1473         /* flush helps the compression for undo-save */
1474         mywrite(wd, MYWRITE_FLUSH, 0);
1475 }
1476
1477 static void write_materials(WriteData *wd, ListBase *idbase)
1478 {
1479         Material *ma;
1480         int a;
1481
1482         ma= idbase->first;
1483         while(ma) {
1484                 if(ma->id.us>0 || wd->current) {
1485                         /* write LibData */
1486                         writestruct(wd, ID_MA, "Material", 1, ma);
1487                         
1488                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1489                           of library blocks that implement this.*/
1490                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1491                           set yet :) */
1492                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1493                         
1494                         if (ma->adt) write_animdata(wd, ma->adt);
1495
1496                         for(a=0; a<MAX_MTEX; a++) {
1497                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1498                         }
1499                         
1500                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1501                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1502                         
1503                         write_scriptlink(wd, &ma->scriptlink);
1504                         
1505                         /* nodetree is integral part of material, no libdata */
1506                         if(ma->nodetree) {
1507                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1508                                 write_nodetree(wd, ma->nodetree);
1509                         }
1510
1511                         write_previews(wd, ma->preview);                        
1512                 }
1513                 ma= ma->id.next;
1514         }
1515 }
1516
1517 static void write_worlds(WriteData *wd, ListBase *idbase)
1518 {
1519         World *wrld;
1520         int a;
1521
1522         wrld= idbase->first;
1523         while(wrld) {
1524                 if(wrld->id.us>0 || wd->current) {
1525                         /* write LibData */
1526                         writestruct(wd, ID_WO, "World", 1, wrld);
1527                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1528                         
1529                         if (wrld->adt) write_animdata(wd, wrld->adt);
1530                         
1531                         for(a=0; a<MAX_MTEX; a++) {
1532                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1533                         }
1534                         
1535                         write_scriptlink(wd, &wrld->scriptlink);
1536                         
1537                         write_previews(wd, wrld->preview);
1538                 }
1539                 wrld= wrld->id.next;
1540         }
1541 }
1542
1543 static void write_lamps(WriteData *wd, ListBase *idbase)
1544 {
1545         Lamp *la;
1546         int a;
1547
1548         la= idbase->first;
1549         while(la) {
1550                 if(la->id.us>0 || wd->current) {
1551                         /* write LibData */
1552                         writestruct(wd, ID_LA, "Lamp", 1, la);
1553                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1554                         
1555                         if (la->adt) write_animdata(wd, la->adt);
1556                         
1557                         /* direct data */
1558                         for(a=0; a<MAX_MTEX; a++) {
1559                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1560                         }
1561                         
1562                         if(la->curfalloff)
1563                                 write_curvemapping(wd, la->curfalloff); 
1564                         
1565                         write_scriptlink(wd, &la->scriptlink);
1566                         
1567                         write_previews(wd, la->preview);
1568                         
1569                 }
1570                 la= la->id.next;
1571         }
1572 }
1573
1574
1575 static void write_scenes(WriteData *wd, ListBase *scebase)
1576 {
1577         Scene *sce;
1578         Base *base;
1579         Editing *ed;
1580         Sequence *seq;
1581         MetaStack *ms;
1582         Strip *strip;
1583         TimeMarker *marker;
1584         TransformOrientation *ts;
1585         SceneRenderLayer *srl;
1586         
1587         sce= scebase->first;
1588         while(sce) {
1589                 /* write LibData */
1590                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1591                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1592                 
1593                 if (sce->adt) write_animdata(wd, sce->adt);
1594                 write_keyingsets(wd, &sce->keyingsets);
1595                 
1596                 /* direct data */
1597                 base= sce->base.first;
1598                 while(base) {
1599                         writestruct(wd, DATA, "Base", 1, base);
1600                         base= base->next;
1601                 }
1602                 
1603                 writestruct(wd, DATA, "ToolSettings", 1, sce->toolsettings);
1604                 if(sce->toolsettings->vpaint)
1605                         writestruct(wd, DATA, "VPaint", 1, sce->toolsettings->vpaint);
1606                 if(sce->toolsettings->wpaint)
1607                         writestruct(wd, DATA, "VPaint", 1, sce->toolsettings->wpaint);
1608                 if(sce->toolsettings->sculpt)
1609                         writestruct(wd, DATA, "Sculpt", 1, sce->toolsettings->sculpt);
1610
1611                 ed= sce->ed;
1612                 if(ed) {
1613                         writestruct(wd, DATA, "Editing", 1, ed);
1614                         
1615                         /* reset write flags too */
1616                         
1617                         SEQ_BEGIN(ed, seq) {
1618                                 if(seq->strip) seq->strip->done= 0;
1619                                 writestruct(wd, DATA, "Sequence", 1, seq);
1620                         }
1621                         SEQ_END
1622                         
1623                         SEQ_BEGIN(ed, seq) {
1624                                 if(seq->strip && seq->strip->done==0) {
1625                                         /* write strip with 'done' at 0 because readfile */
1626                                         
1627                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1628                                         if(seq->effectdata) {
1629                                                 switch(seq->type){
1630                                                 case SEQ_COLOR:
1631                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
1632                                                         break;
1633                                                 case SEQ_SPEED:
1634                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
1635                                                         break;
1636                                                 case SEQ_WIPE:
1637                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1638                                                         break;
1639                                                 case SEQ_GLOW:
1640                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1641                                                         break;
1642                                                 case SEQ_TRANSFORM:
1643                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
1644                                                         break;
1645                                                 }
1646                                         }
1647                                         
1648                                         strip= seq->strip;
1649                                         writestruct(wd, DATA, "Strip", 1, strip);
1650                                         if(seq->flag & SEQ_USE_CROP && strip->crop) {
1651                                                 writestruct(wd, DATA, "StripCrop", 1, strip->crop);
1652                                         }
1653                                         if(seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
1654                                                 writestruct(wd, DATA, "StripTransform", 1, strip->transform);
1655                                         }
1656                                         if(seq->flag & SEQ_USE_PROXY && strip->proxy) {
1657                                                 writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
1658                                         }
1659                                         if(seq->flag & SEQ_USE_COLOR_BALANCE && strip->color_balance) {
1660                                                 writestruct(wd, DATA, "StripColorBalance", 1, strip->color_balance);
1661                                         }
1662                                         if(seq->type==SEQ_IMAGE)
1663                                                 writestruct(wd, DATA, "StripElem", MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem), strip->stripdata);
1664                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
1665                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1666                                         
1667                                         strip->done= 1;
1668                                 }
1669                         }
1670                         SEQ_END
1671                                 
1672                         /* new; meta stack too, even when its nasty restore code */
1673                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1674                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1675                         }
1676                 }
1677                 
1678                 write_scriptlink(wd, &sce->scriptlink);
1679                 
1680                 if (sce->r.avicodecdata) {
1681                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1682                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1683                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1684                 }
1685
1686                 if (sce->r.qtcodecdata) {
1687                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1688                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1689                 }
1690                 if (sce->r.ffcodecdata.properties) {
1691                         IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
1692                 }
1693
1694                 /* writing dynamic list of TimeMarkers to the blend file */
1695                 for(marker= sce->markers.first; marker; marker= marker->next)
1696                         writestruct(wd, DATA, "TimeMarker", 1, marker);
1697                 
1698                 /* writing dynamic list of TransformOrientations to the blend file */
1699                 for(ts = sce->transform_spaces.first; ts; ts = ts->next)
1700                         writestruct(wd, DATA, "TransformOrientation", 1, ts);
1701                 
1702                 for(srl= sce->r.layers.first; srl; srl= srl->next)
1703                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
1704                 
1705                 if(sce->nodetree) {
1706                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
1707                         write_nodetree(wd, sce->nodetree);
1708                 }
1709                 
1710                 sce= sce->id.next;
1711         }
1712         /* flush helps the compression for undo-save */
1713         mywrite(wd, MYWRITE_FLUSH, 0);
1714 }
1715
1716 static void write_gpencils(WriteData *wd, ListBase *lb)
1717 {
1718         bGPdata *gpd;
1719         bGPDlayer *gpl;
1720         bGPDframe *gpf;
1721         bGPDstroke *gps;
1722         
1723         for (gpd= lb->first; gpd; gpd= gpd->id.next) {
1724                 /* write gpd data block to file */
1725                 writestruct(wd, ID_GD, "bGPdata", 1, gpd);
1726                 
1727                 /* write grease-pencil layers to file */
1728                 for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
1729                         writestruct(wd, DATA, "bGPDlayer", 1, gpl);
1730                         
1731                         /* write this layer's frames to file */
1732                         for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
1733                                 writestruct(wd, DATA, "bGPDframe", 1, gpf);
1734                                 
1735                                 /* write strokes */
1736                                 for (gps= gpf->strokes.first; gps; gps= gps->next) {
1737                                         writestruct(wd, DATA, "bGPDstroke", 1, gps);
1738                                         writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);                               
1739                                 }
1740                         }
1741                 }
1742         }
1743 }
1744
1745 static void write_windowmanagers(WriteData *wd, ListBase *lb)
1746 {
1747         wmWindowManager *wm;
1748         wmWindow *win;
1749         
1750         for(wm= lb->first; wm; wm= wm->id.next) {
1751                 writestruct(wd, ID_WM, "wmWindowManager", 1, wm);
1752                 
1753                 for(win= wm->windows.first; win; win= win->next)
1754                         writestruct(wd, DATA, "wmWindow", 1, win);
1755         }
1756 }
1757
1758 static void write_region(WriteData *wd, ARegion *ar, int spacetype)
1759 {       
1760         writestruct(wd, DATA, "ARegion", 1, ar);
1761         
1762         if(ar->regiondata) {
1763                 switch(spacetype) {
1764                         case SPACE_VIEW3D:
1765                                 if(ar->regiontype==RGN_TYPE_WINDOW) {
1766                                         RegionView3D *rv3d= ar->regiondata;
1767                                         writestruct(wd, DATA, "RegionView3D", 1, rv3d);
1768                                         
1769                                         if(rv3d->localvd)
1770                                                 writestruct(wd, DATA, "RegionView3D", 1, rv3d->localvd);
1771                                         if(rv3d->clipbb) 
1772                                                 writestruct(wd, DATA, "BoundBox", 1, rv3d->clipbb);
1773
1774                                 }
1775                                 else
1776                                         printf("regiondata write missing!\n");
1777                                 break;
1778                         default:
1779                                 printf("regiondata write missing!\n");
1780                 }
1781         }
1782 }
1783
1784 static void write_screens(WriteData *wd, ListBase *scrbase)
1785 {
1786         bScreen *sc;
1787         ScrArea *sa;
1788         ScrVert *sv;
1789         ScrEdge *se;
1790
1791         sc= scrbase->first;
1792         while(sc) {
1793                 
1794                 /* write LibData */
1795                 /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
1796                 writestruct(wd, ID_SCRN, "Screen", 1, sc);
1797                 if (sc->id.properties) 
1798                         IDP_WriteProperty(sc->id.properties, wd);
1799                 
1800                 /* direct data */
1801                 for(sv= sc->vertbase.first; sv; sv= sv->next)
1802                         writestruct(wd, DATA, "ScrVert", 1, sv);
1803                 
1804                 for(se= sc->edgebase.first; se; se= se->next) 
1805                         writestruct(wd, DATA, "ScrEdge", 1, se);
1806                 
1807                 for(sa= sc->areabase.first; sa; sa= sa->next) {
1808                         SpaceLink *sl;
1809                         Panel *pa;
1810                         ARegion *ar;
1811                         
1812                         writestruct(wd, DATA, "ScrArea", 1, sa);
1813                         
1814                         for(ar= sa->regionbase.first; ar; ar= ar->next) {
1815                                 write_region(wd, ar, sa->spacetype);
1816                                 
1817                                 for(pa= ar->panels.first; pa; pa= pa->next)
1818                                         writestruct(wd, DATA, "Panel", 1, pa);
1819                         }
1820                         
1821                         /* space handler scriptlinks */
1822                         write_scriptlink(wd, &sa->scriptlink);
1823                         
1824                         sl= sa->spacedata.first;
1825                         while(sl) {
1826                                 for(ar= sl->regionbase.first; ar; ar= ar->next)
1827                                         write_region(wd, ar, sl->spacetype);
1828                                 
1829                                 if(sl->spacetype==SPACE_VIEW3D) {
1830                                         View3D *v3d= (View3D *) sl;
1831                                         writestruct(wd, DATA, "View3D", 1, v3d);
1832                                         if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
1833                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
1834                                 }
1835                                 else if(sl->spacetype==SPACE_IPO) {
1836                                         SpaceIpo *sipo= (SpaceIpo *)sl;
1837                                         ListBase tmpGhosts = sipo->ghostCurves;
1838                                         
1839                                         /* temporarily disable ghost curves when saving */
1840                                         sipo->ghostCurves.first= sipo->ghostCurves.last= NULL;
1841                                         
1842                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
1843                                         if(sipo->ads) writestruct(wd, DATA, "bDopeSheet", 1, sipo->ads);
1844                                         
1845                                         /* reenable ghost curves */
1846                                         sipo->ghostCurves= tmpGhosts;
1847                                 }
1848                                 else if(sl->spacetype==SPACE_BUTS) {
1849                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
1850                                 }
1851                                 else if(sl->spacetype==SPACE_FILE) {
1852                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
1853                                 }
1854                                 else if(sl->spacetype==SPACE_SEQ) {
1855                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
1856                                 }
1857                                 else if(sl->spacetype==SPACE_OUTLINER) {
1858                                         SpaceOops *so= (SpaceOops *)sl;
1859                                         
1860                                         writestruct(wd, DATA, "SpaceOops", 1, so);
1861
1862                                         /* outliner */
1863                                         if(so->treestore) {
1864                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
1865                                                 if(so->treestore->data)
1866                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
1867                                         }
1868                                 }
1869                                 else if(sl->spacetype==SPACE_IMAGE) {
1870                                         SpaceImage *sima= (SpaceImage *)sl;
1871                                         
1872                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
1873                                         if(sima->cumap)
1874                                                 write_curvemapping(wd, sima->cumap);
1875                                 }
1876                                 else if(sl->spacetype==SPACE_IMASEL) {
1877                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
1878                                 }
1879                                 else if(sl->spacetype==SPACE_TEXT) {
1880                                         writestruct(wd, DATA, "SpaceText", 1, sl);
1881                                 }
1882                                 else if(sl->spacetype==SPACE_SCRIPT) {
1883                                         SpaceScript *sc = (SpaceScript*)sl;
1884                                         sc->but_refs = NULL;
1885                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
1886                                 }
1887                                 else if(sl->spacetype==SPACE_ACTION) {
1888                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
1889                                 }
1890                                 else if(sl->spacetype==SPACE_SOUND) {
1891                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
1892                                 }
1893                                 else if(sl->spacetype==SPACE_NLA){
1894                                         writestruct(wd, DATA, "SpaceNla", 1, sl);
1895                                 }
1896                                 else if(sl->spacetype==SPACE_TIME){
1897                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
1898                                 }
1899                                 else if(sl->spacetype==SPACE_NODE){
1900                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
1901                                 }
1902                                 else if(sl->spacetype==SPACE_LOGIC){
1903                                         writestruct(wd, DATA, "SpaceLogic", 1, sl);
1904                                 }
1905                                 sl= sl->next;
1906                         }
1907                 }
1908
1909                 sc= sc->id.next;
1910         }
1911 }
1912
1913 static void write_libraries(WriteData *wd, Main *main)
1914 {
1915         ListBase *lbarray[30];
1916         ID *id;
1917         int a, tot, foundone;
1918
1919         for(; main; main= main->next) {
1920
1921                 a=tot= set_listbasepointers(main, lbarray);
1922
1923                 /* test: is lib being used */
1924                 foundone= 0;
1925                 while(tot--) {
1926                         for(id= lbarray[tot]->first; id; id= id->next) {
1927                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
1928                                         foundone= 1;
1929                                         break;
1930                                 }
1931                         }
1932                         if(foundone) break;
1933                 }
1934
1935                 if(foundone) {
1936                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
1937
1938                         while(a--) {
1939                                 for(id= lbarray[a]->first; id; id= id->next) {
1940                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
1941                                                 writestruct(wd, ID_ID, "ID", 1, id);
1942                                         }
1943                                 }
1944                         }
1945                 }
1946         }
1947 }
1948
1949 static void write_bone(WriteData *wd, Bone* bone)
1950 {
1951         Bone*   cbone;
1952
1953         // PATCH for upward compatibility after 2.37+ armature recode
1954         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
1955                 
1956         // Write this bone
1957         writestruct(wd, DATA, "Bone", 1, bone);
1958         
1959         // Write Children
1960         cbone= bone->childbase.first;
1961         while(cbone) {
1962                 write_bone(wd, cbone);
1963                 cbone= cbone->next;
1964         }
1965 }
1966
1967 static void write_armatures(WriteData *wd, ListBase *idbase)
1968 {
1969         bArmature       *arm;
1970         Bone            *bone;
1971
1972         arm=idbase->first;
1973         while (arm) {
1974                 if (arm->id.us>0 || wd->current) {
1975                         writestruct(wd, ID_AR, "bArmature", 1, arm);
1976                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
1977
1978                         /* Direct data */
1979                         bone= arm->bonebase.first;
1980                         while(bone) {
1981                                 write_bone(wd, bone);
1982                                 bone=bone->next;
1983                         }
1984                 }
1985                 arm=arm->id.next;
1986         }
1987
1988         /* flush helps the compression for undo-save */
1989         mywrite(wd, MYWRITE_FLUSH, 0);
1990 }
1991
1992 static void write_texts(WriteData *wd, ListBase *idbase)
1993 {
1994         Text *text;
1995         TextLine *tmp;
1996         TextMarker *mrk;
1997
1998         text= idbase->first;
1999         while(text) {
2000                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
2001
2002                 /* write LibData */
2003                 writestruct(wd, ID_TXT, "Text", 1, text);
2004                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
2005                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
2006
2007                 if(!(text->flags & TXT_ISEXT)) {
2008                         /* now write the text data, in two steps for optimization in the readfunction */
2009                         tmp= text->lines.first;
2010                         while (tmp) {
2011                                 writestruct(wd, DATA, "TextLine", 1, tmp);
2012                                 tmp= tmp->next;
2013                         }
2014
2015                         tmp= text->lines.first;
2016                         while (tmp) {
2017                                 writedata(wd, DATA, tmp->len+1, tmp->line);
2018                                 tmp= tmp->next;
2019                         }
2020
2021                         /* write markers */
2022                         mrk= text->markers.first;
2023                         while (mrk) {
2024                                 writestruct(wd, DATA, "TextMarker", 1, mrk);
2025                                 mrk= mrk->next;
2026                         }
2027                 }
2028
2029
2030                 text= text->id.next;
2031         }
2032
2033         /* flush helps the compression for undo-save */
2034         mywrite(wd, MYWRITE_FLUSH, 0);
2035 }
2036
2037 static void write_sounds(WriteData *wd, ListBase *idbase)
2038 {
2039         bSound *sound;
2040         bSample *sample;
2041
2042         PackedFile * pf;
2043
2044         // set all samples to unsaved status
2045
2046         sample = samples->first; // samples is a global defined in sound.c
2047         while (sample) {
2048                 sample->flags |= SAMPLE_NEEDS_SAVE;
2049                 sample = sample->id.next;
2050         }
2051
2052         sound= idbase->first;
2053         while(sound) {
2054                 if(sound->id.us>0 || wd->current) {
2055                         // do we need to save the packedfile as well ?
2056                         sample = sound->sample;
2057                         if (sample) {
2058                                 if (sample->flags & SAMPLE_NEEDS_SAVE) {
2059                                         sound->newpackedfile = sample->packedfile;
2060                                         sample->flags &= ~SAMPLE_NEEDS_SAVE;
2061                                 } else {
2062                                         sound->newpackedfile = NULL;
2063                                 }
2064                         }
2065
2066                         /* write LibData */
2067                         writestruct(wd, ID_SO, "bSound", 1, sound);
2068                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
2069
2070                         if (sound->newpackedfile) {
2071                                 pf = sound->newpackedfile;
2072                                 writestruct(wd, DATA, "PackedFile", 1, pf);
2073                                 writedata(wd, DATA, pf->size, pf->data);
2074                         }
2075
2076                         if (sample) {
2077                                 sound->newpackedfile = sample->packedfile;
2078                         }
2079                 }
2080                 sound= sound->id.next;
2081         }
2082
2083         /* flush helps the compression for undo-save */
2084         mywrite(wd, MYWRITE_FLUSH, 0);
2085 }
2086
2087 static void write_groups(WriteData *wd, ListBase *idbase)
2088 {
2089         Group *group;
2090         GroupObject *go;
2091
2092         for(group= idbase->first; group; group= group->id.next) {
2093                 if(group->id.us>0 || wd->current) {
2094                         /* write LibData */
2095                         writestruct(wd, ID_GR, "Group", 1, group);
2096                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
2097
2098                         go= group->gobject.first;
2099                         while(go) {
2100                                 writestruct(wd, DATA, "GroupObject", 1, go);
2101                                 go= go->next;
2102                         }
2103                 }
2104         }
2105 }
2106
2107 static void write_nodetrees(WriteData *wd, ListBase *idbase)
2108 {
2109         bNodeTree *ntree;
2110         
2111         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
2112                 if (ntree->id.us>0 || wd->current) {
2113                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
2114                         write_nodetree(wd, ntree);
2115                         
2116                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
2117                         
2118                         if (ntree->adt) write_animdata(wd, ntree->adt);
2119                 }
2120         }
2121 }
2122
2123 static void write_brushes(WriteData *wd, ListBase *idbase)
2124 {
2125         Brush *brush;
2126         int a;
2127         
2128         for(brush=idbase->first; brush; brush= brush->id.next) {
2129                 if(brush->id.us>0 || wd->current) {
2130                         writestruct(wd, ID_BR, "Brush", 1, brush);
2131                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
2132                         for(a=0; a<MAX_MTEX; a++)
2133                                 if(brush->mtex[a])
2134                                         writestruct(wd, DATA, "MTex", 1, brush->mtex[a]);
2135
2136                         if(brush->curve)
2137                                 write_curvemapping(wd, brush->curve);
2138                 }
2139         }
2140 }
2141
2142 static void write_scripts(WriteData *wd, ListBase *idbase)
2143 {
2144         Script *script;
2145         
2146         for(script=idbase->first; script; script= script->id.next) {
2147                 if(script->id.us>0 || wd->current) {
2148                         writestruct(wd, ID_SCRIPT, "Script", 1, script);
2149                         if (script->id.properties) IDP_WriteProperty(script->id.properties, wd);
2150                 }
2151         }
2152 }
2153
2154 /* context is usually defined by WM, two cases where no WM is available:
2155  * - for forward compatibility, curscreen has to be saved
2156  * - for undofile, curscene needs to be saved */
2157 static void write_global(WriteData *wd, Main *mainvar)
2158 {
2159         FileGlobal fg;
2160         bScreen *screen;
2161         char subvstr[8];
2162         
2163         current_screen_compat(mainvar, &screen);
2164
2165         /* XXX still remap G */
2166         fg.curscreen= screen;
2167         fg.curscene= screen->scene;
2168         fg.displaymode= G.displaymode;
2169         fg.winpos= G.winpos;
2170         fg.fileflags= (G.fileflags & ~G_FILE_NO_UI);    // prevent to save this, is not good convention, and feature with concerns...
2171         fg.globalf= G.f;
2172
2173         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
2174         memcpy(fg.subvstr, subvstr, 4);
2175         
2176         fg.subversion= BLENDER_SUBVERSION;
2177         fg.minversion= BLENDER_MINVERSION;
2178         fg.minsubversion= BLENDER_MINSUBVERSION;
2179         fg.pads= 0; /* prevent mem checkers from complaining */
2180         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
2181 }
2182
2183 /* if MemFile * there's filesave to memory */
2184 static int write_file_handle(Main *mainvar, int handle, MemFile *compare, MemFile *current, 
2185                                                          int write_user_block, int write_flags)
2186 {
2187         BHead bhead;
2188         ListBase mainlist;
2189         char buf[16];
2190         WriteData *wd;
2191
2192         blo_split_main(&mainlist, mainvar);
2193
2194         wd= bgnwrite(handle, compare, current, write_flags);
2195         
2196         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (ENDIAN_ORDER==B_ENDIAN)?'V':'v', BLENDER_VERSION);
2197         mywrite(wd, buf, 12);
2198
2199         write_renderinfo(wd, mainvar);
2200         write_global(wd, mainvar);
2201
2202         /* no UI save in undo */
2203         if(current==NULL) {
2204                 write_windowmanagers(wd, &mainvar->wm);
2205                 write_screens  (wd, &mainvar->screen);
2206         }
2207         write_scenes   (wd, &mainvar->scene);
2208         write_curves   (wd, &mainvar->curve);
2209         write_mballs   (wd, &mainvar->mball);
2210         write_images   (wd, &mainvar->image);
2211         write_cameras  (wd, &mainvar->camera);
2212         write_lamps    (wd, &mainvar->lamp);
2213         write_lattices (wd, &mainvar->latt);
2214         write_vfonts   (wd, &mainvar->vfont);
2215         write_keys     (wd, &mainvar->key);
2216         write_worlds   (wd, &mainvar->world);
2217         write_texts    (wd, &mainvar->text);
2218         write_sounds   (wd, &mainvar->sound);
2219         write_groups   (wd, &mainvar->group);
2220         write_armatures(wd, &mainvar->armature);
2221         write_actions  (wd, &mainvar->action);
2222         write_objects  (wd, &mainvar->object, (current != NULL));
2223         write_materials(wd, &mainvar->mat);
2224         write_textures (wd, &mainvar->tex);
2225         write_meshs    (wd, &mainvar->mesh);
2226         write_particlesettings(wd, &mainvar->particle);
2227         write_nodetrees(wd, &mainvar->nodetree);
2228         write_brushes  (wd, &mainvar->brush);
2229         write_scripts  (wd, &mainvar->script);
2230         write_gpencils (wd, &mainvar->gpencil);
2231         if(current==NULL)       
2232                 write_libraries(wd,  mainvar->next); /* no library save in undo */
2233
2234         if (write_user_block) {
2235                 write_userdef(wd);
2236         }
2237                                                         
2238         /* dna as last, because (to be implemented) test for which structs are written */
2239         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
2240
2241         /* end of file */
2242         memset(&bhead, 0, sizeof(BHead));
2243         bhead.code= ENDB;
2244         mywrite(wd, &bhead, sizeof(BHead));
2245
2246         blo_join_main(&mainlist);
2247
2248         return endwrite(wd);
2249 }
2250
2251 /* return: success (1) */
2252 int BLO_write_file(Main *mainvar, char *dir, int write_flags, ReportList *reports)
2253 {
2254         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
2255         char tempname[FILE_MAXDIR+FILE_MAXFILE];
2256         int file, err, write_user_block;
2257
2258         sprintf(tempname, "%s@", dir);
2259
2260         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
2261         if(file == -1) {
2262                 BKE_report(reports, RPT_ERROR, "Unable to open file for writing.");
2263                 return 0;
2264         }
2265
2266         BLI_make_file_string(G.sce, userfilename, BLI_gethome(), ".B25.blend");
2267         write_user_block= BLI_streq(dir, userfilename);
2268
2269         err= write_file_handle(mainvar, file, NULL,NULL, write_user_block, write_flags);
2270         close(file);
2271
2272         if(!err) {
2273                 if(write_flags & G_FILE_COMPRESS)
2274                 {       
2275                         // compressed files have the same ending as regular files... only from 2.4!!!
2276                         
2277                         int ret = BLI_gzip(tempname, dir);
2278                         
2279                         if(-1==ret) {
2280                                 BKE_report(reports, RPT_ERROR, "Failed opening .gz file.");
2281                                 return 0;
2282                         }
2283                         if(-2==ret) {
2284                                 BKE_report(reports, RPT_ERROR, "Failed opening .blend file for compression.");
2285                                 return 0;
2286                         }
2287                 }
2288                 else
2289                 if(BLI_rename(tempname, dir) != 0) {
2290                         BKE_report(reports, RPT_ERROR, "Can't change old file. File saved with @");
2291                         return 0;
2292                 }
2293
2294                 
2295         } else {
2296                 BKE_report(reports, RPT_ERROR, strerror(errno));
2297                 remove(tempname);
2298
2299                 return 0;
2300         }
2301
2302         return 1;
2303 }
2304
2305 /* return: success (1) */
2306 int BLO_write_file_mem(Main *mainvar, MemFile *compare, MemFile *current, int write_flags, ReportList *reports)
2307 {
2308         int err;
2309
2310         err= write_file_handle(mainvar, 0, compare, current, 0, write_flags);
2311         
2312         if(err==0) return 1;
2313         return 0;
2314 }
2315
2316
2317         /* Runtime writing */
2318
2319 #ifdef WIN32
2320 #define PATHSEPERATOR           "\\"
2321 #else
2322 #define PATHSEPERATOR           "/"
2323 #endif
2324
2325 static char *get_runtime_path(char *exename) {
2326         char *installpath= get_install_dir();
2327
2328         if (!installpath) {
2329                 return NULL;
2330         } else {
2331                 char *path= MEM_mallocN(strlen(installpath)+strlen(PATHSEPERATOR)+strlen(exename)+1, "runtimepath");
2332
2333                 if (path == NULL) {
2334                         MEM_freeN(installpath);
2335                         return NULL;
2336                 }
2337
2338                 strcpy(path, installpath);
2339                 strcat(path, PATHSEPERATOR);
2340                 strcat(path, exename);
2341
2342                 MEM_freeN(installpath);
2343
2344                 return path;
2345         }
2346 }
2347
2348 #ifdef __APPLE__
2349
2350 static int recursive_copy_runtime(char *outname, char *exename, ReportList *reports)
2351 {
2352         char *runtime = get_runtime_path(exename);
2353         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
2354         int progfd = -1, error= 0;
2355
2356         if (!runtime) {
2357                 BKE_report(reports, RPT_ERROR, "Unable to find runtime");
2358                 error= 1;
2359                 goto cleanup;
2360         }
2361         //printf("runtimepath %s\n", runtime);
2362                 
2363         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2364         if (progfd==-1) {
2365                 BKE_report(reports, RPT_ERROR, "Unable to find runtime");
2366                 error= 1;
2367                 goto cleanup;
2368         }
2369
2370         sprintf(command, "/bin/cp -R \"%s\" \"%s\"", runtime, outname);
2371         //printf("command %s\n", command);
2372         if (system(command) == -1) {
2373                 BKE_report(reports, RPT_ERROR, "Couldn't copy runtime");
2374                 error= 1;
2375         }
2376
2377 cleanup:
2378         if (progfd!=-1)
2379                 close(progfd);
2380         if (runtime)
2381                 MEM_freeN(runtime);
2382
2383         return !error;
2384 }
2385
2386 int BLO_write_runtime(Main *mainvar, char *file, char *exename, ReportList *reports) 
2387 {
2388         char gamename[FILE_MAXDIR+FILE_MAXFILE];
2389         int outfd = -1, error= 0;
2390
2391         // remove existing file / bundle
2392         //printf("Delete file %s\n", file);
2393         BLI_delete(file, 0, TRUE);
2394
2395         if (!recursive_copy_runtime(file, exename, reports)) {
2396                 error= 1;
2397                 goto cleanup;
2398         }
2399
2400         strcpy(gamename, file);
2401         strcat(gamename, "/Contents/Resources/game.blend");
2402         //printf("gamename %s\n", gamename);
2403         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2404         if (outfd != -1) {
2405
2406                 write_file_handle(mainvar, outfd, NULL,NULL, 0, G.fileflags);
2407
2408                 if (write(outfd, " ", 1) != 1) {
2409                         BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2410                         error= 1;
2411                         goto cleanup;
2412                 }
2413         } else {
2414                 BKE_report(reports, RPT_ERROR, "Unable to open blenderfile.");
2415                 error= 1;
2416         }
2417
2418 cleanup:
2419         if (outfd!=-1)
2420                 close(outfd);
2421
2422         BKE_reports_prepend(reports, "Unable to make runtime: ");
2423         return !error;
2424 }
2425
2426 #else /* !__APPLE__ */
2427
2428 static int handle_append_runtime(int handle, char *exename, ReportList *reports)
2429 {
2430         char *runtime= get_runtime_path(exename);
2431         unsigned char buf[1024];
2432         int count, progfd= -1, error= 0;
2433
2434         if (!BLI_exists(runtime)) {
2435                 BKE_report(reports, RPT_ERROR, "Unable to find runtime.");
2436                 error= 1;
2437                 goto cleanup;
2438         }
2439
2440         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2441         if (progfd==-1) {
2442                 BKE_report(reports, RPT_ERROR, "Unable to find runtime.@");
2443                 error= 1;
2444                 goto cleanup;
2445         }
2446
2447         while ((count= read(progfd, buf, sizeof(buf)))>0) {
2448                 if (write(handle, buf, count)!=count) {
2449                         BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2450                         error= 1;
2451                         goto cleanup;
2452                 }
2453         }
2454
2455 cleanup:
2456         if (progfd!=-1)
2457                 close(progfd);
2458         if (runtime)
2459                 MEM_freeN(runtime);
2460
2461         return !error;
2462 }
2463
2464 static int handle_write_msb_int(int handle, int i) 
2465 {
2466         unsigned char buf[4];
2467         buf[0]= (i>>24)&0xFF;
2468         buf[1]= (i>>16)&0xFF;
2469         buf[2]= (i>>8)&0xFF;
2470         buf[3]= (i>>0)&0xFF;
2471
2472         return (write(handle, buf, 4)==4);
2473 }
2474
2475 int BLO_write_runtime(Main *mainvar, char *file, char *exename, ReportList *reports)
2476 {
2477         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2478         int datastart, error= 0;
2479
2480         if (!outfd) {
2481                 BKE_report(reports, RPT_ERROR, "Unable to open output file.");
2482                 error= 1;
2483                 goto cleanup;
2484         }
2485         if (!handle_append_runtime(outfd, exename, reports)) {
2486                 error= 1;
2487                 goto cleanup;
2488         }
2489
2490         datastart= lseek(outfd, 0, SEEK_CUR);
2491
2492         write_file_handle(mainvar, outfd, NULL,NULL, 0, G.fileflags);
2493
2494         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
2495                 BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2496                 error= 1;
2497                 goto cleanup;
2498         }
2499
2500 cleanup:
2501         if (outfd!=-1)
2502                 close(outfd);
2503
2504         BKE_reports_prepend(reports, "Unable to make runtime: ");
2505         return !error;
2506 }
2507
2508 #endif /* !__APPLE__ */