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