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