This commit removes the glue from Blender, and with it
[blender.git] / source / blender / blenloader / intern / writefile.c
1 /* writefile.c
2  *
3  * .blend file writing
4  *
5  * $Id$
6  *
7  * ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; either version 2
12  * of the License, or (at your option) any later version. The Blender
13  * Foundation also sells licenses for use in proprietary software under
14  * the Blender License.  See http://www.blender.org/BL/ for information
15  * about this.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software Foundation,
24  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25  *
26  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
27  * All rights reserved.
28  *
29  * The Original Code is: all of this file.
30  *
31  * Contributor(s): none yet.
32  *
33  * ***** END GPL/BL DUAL LICENSE BLOCK *****
34  */
35
36 /*
37 FILEFORMAT: IFF-style structure  (but not IFF compatible!)
38  
39 start file:
40         BLENDER_V100    12 bytes  (versie 1.00)
41                                         V = big endian, v = little endian
42                                         _ = 4 byte pointer, - = 8 byte pointer
43
44 datablocks:             also see struct BHead
45         <bh.code>                       4 chars
46         <bh.len>                        int,  len data after BHead
47         <bh.old>                        void,  old pointer
48         <bh.SDNAnr>                     int
49         <bh.nr>                         int, in case of array: amount of structs
50         data                    
51         ...
52         ...
53
54 Almost all data in Blender are structures. Each struct saved
55 gets a BHead header.  With BHead the struct can be linked again
56 and compared with StructDNA .
57
58 WRITE
59
60 Preferred writing order: (not really a must, but why would you do it random?)
61 Any case: direct data is ALWAYS after the lib block
62
63 (Local file data)
64 - for each LibBlock
65         - write LibBlock
66         - write associated direct data
67 (External file data)
68 - per library
69         - write library block
70         - per LibBlock
71                 - write the ID of LibBlock
72 - write FileGlobal (some global vars)
73 - write SDNA
74 - write USER if filename is ~/.B.blend
75 */
76
77 /* for version 2.2+
78 Important to know is that 'streaming' has been added to files, for Blender Publisher
79 */
80
81
82 #ifdef HAVE_CONFIG_H
83 #include <config.h>
84 #endif
85
86 #ifndef WIN32 
87 #include <unistd.h>
88 #else
89 #include "winsock2.h"
90 #include "BLI_winstuff.h"
91 #include <io.h>
92 #include <process.h> // for getpid
93 #endif
94
95 #include <math.h>
96 #include <fcntl.h>
97 #include <stdio.h>
98 #include <string.h>
99 #include <stdlib.h>
100
101 #include "nla.h" //  __NLA is defined
102
103 #include "DNA_packedFile_types.h"
104 #include "DNA_sdna_types.h"
105 #include "DNA_property_types.h"
106 #include "DNA_sensor_types.h"
107 #include "DNA_controller_types.h"
108 #include "DNA_actuator_types.h"
109 #include "DNA_effect_types.h"
110 #include "DNA_object_types.h"
111 #include "DNA_userdef_types.h"
112 #include "DNA_vfont_types.h"
113 #include "DNA_ipo_types.h"
114 #include "DNA_curve_types.h"
115 #include "DNA_camera_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_lattice_types.h"
121 #include "DNA_armature_types.h"
122 #include "DNA_sequence_types.h"
123 #include "DNA_ika_types.h"
124 #include "DNA_group_types.h"
125 #include "DNA_oops_types.h"
126 #include "DNA_space_types.h"
127 #include "DNA_screen_types.h"
128 #include "DNA_view3d_types.h"
129 #include "DNA_lamp_types.h"
130 #include "DNA_fileglobal_types.h"
131 #include "DNA_sound_types.h"
132 #include "DNA_texture_types.h"
133 #include "DNA_text_types.h"
134 #include "DNA_image_types.h"
135 #include "DNA_key_types.h"
136 #include "DNA_scene_types.h"
137 #include "DNA_constraint_types.h"
138 #include "DNA_listBase.h" /* for Listbase, the type of samples, ...*/
139 #include "DNA_action_types.h"
140 #include "DNA_nla_types.h"
141
142 #include "MEM_guardedalloc.h" // MEM_freeN 
143 #include "BLI_blenlib.h"
144 #include "BLI_linklist.h"
145
146 #include "BKE_action.h"
147 #include "BKE_utildefines.h" // for KNOTSU KNOTSV WHILE_SEQ END_SEQ defines
148 #include "BKE_bad_level_calls.h" // build_seqar (from WHILE_SEQ) free_oops error
149 #include "BKE_constraint.h"
150 #include "BKE_main.h" // G.main
151 #include "BKE_global.h" // for G
152 #include "BKE_screen.h" // for waitcursor
153 #include "BKE_packedFile.h" // for packAll
154 #include "BKE_library.h" // for  set_listbasepointers
155 #include "BKE_sound.h" /* ... and for samples */
156
157 #include "GEN_messaging.h"
158
159 #include "BLO_writefile.h"
160 #include "BLO_readfile.h"
161
162 #include "readfile.h"
163 #include "genfile.h"
164
165 typedef struct {
166         struct SDNA *sdna;
167
168         int file;
169         unsigned char *buf;
170         
171         int tot, count, error;
172 } WriteData;
173
174 static WriteData *writedata_new(int file)
175 {
176         extern char DNAstr[];   /* DNA.c */
177         extern int DNAlen;
178         
179         WriteData *wd= MEM_callocN(sizeof(*wd), "writedata");
180
181                 /* XXX, see note about this in readfile.c, remove
182                  * once we have an xp lock - zr
183                  */
184         wd->sdna= dna_sdna_from_data(DNAstr, DNAlen, 0);
185         
186         wd->file= file;
187
188         wd->buf= MEM_mallocN(100000, "wd->buf");
189         
190         return wd;
191 }
192
193 static void writedata_do_write(WriteData *wd, void *mem, int memlen)
194 {
195         if (wd->error) return;
196         if (write(wd->file, mem, memlen) != memlen)
197                 wd->error= 1;
198 }
199
200 static void writedata_free(WriteData *wd) 
201 {
202         dna_freestructDNA(wd->sdna);
203
204         MEM_freeN(wd->buf);
205         MEM_freeN(wd);
206 }
207
208 /***/
209
210 int mywfile;
211
212 /**
213  * Low level WRITE(2) wrapper that buffers data
214  * @param adr Pointer to new chunk of data
215  * @param len Length of new chunk of data
216  * @warning Talks to other functions with global parameters
217  */
218         static void
219 mywrite(
220         WriteData *wd, 
221         void *adr,
222         int len)
223 {
224         if (wd->error) return;
225
226         wd->tot+= len;
227
228         if(len>50000) {
229                 if(wd->count) {
230                         writedata_do_write(wd, wd->buf, wd->count);
231                         wd->count= 0;
232                 }
233                 writedata_do_write(wd, adr, len);
234                 return;
235         }
236         if(len+wd->count>99999) {
237                 writedata_do_write(wd, wd->buf, wd->count);
238                 wd->count= 0; 
239         }
240         memcpy(&wd->buf[wd->count], adr, len);
241         wd->count+= len;
242 }
243
244 /**
245  * BeGiN initializer for mywrite
246  * @param file File descriptor
247  * @param write_flags Write parameters
248  * @warning Talks to other functions with global parameters
249  */
250         static WriteData *
251 bgnwrite(
252         int file, 
253         int write_flags)
254 {
255         WriteData *wd= writedata_new(file);
256         
257         return wd;
258 }
259
260 /**
261  * END the mywrite wrapper
262  * @return 1 if write failed
263  * @return unknown global variable otherwise
264  * @warning Talks to other functions with global parameters
265  */
266         static int
267 endwrite(
268         WriteData *wd)
269 {
270         int err;
271         
272         if (wd->count) {
273                 writedata_do_write(wd, wd->buf, wd->count);
274                 wd->count= 0; 
275         }
276         
277         err= wd->error;
278         writedata_free(wd);
279         
280         return err;
281 }
282
283 /* ********** WRITE FILE ****************** */
284
285 static void writestruct(WriteData *wd, int filecode, char *structname, int nr, void *adr)
286 {
287         BHead bh;
288         short *sp;
289         
290         if(adr==0 || nr==0) return;
291         
292         /* init BHead */
293         bh.code= filecode;
294         bh.old= adr;
295         bh.nr= nr;
296         
297         bh.SDNAnr= dna_findstruct_nr(wd->sdna, structname);
298         if(bh.SDNAnr== -1) {
299                 printf("error: can't find SDNA code %s\n", structname);
300                 return;
301         }
302         sp= wd->sdna->structs[bh.SDNAnr];
303         
304         bh.len= nr*wd->sdna->typelens[sp[0]];
305         
306         if(bh.len==0) return;
307                 
308         mywrite(wd, &bh, sizeof(BHead));
309         mywrite(wd, adr, bh.len);
310 }
311
312 static void writedata(WriteData *wd, int filecode, int len, void *adr)  /* do not use for structs */
313 {
314         BHead bh;
315         
316         if(adr==0) return;
317         if(len==0) return;
318         
319         len+= 3;
320         len-= ( len % 4);
321         
322         /* init BHead */
323         bh.code= filecode;
324         bh.old= adr;
325         bh.nr= 1;
326         bh.SDNAnr= 0;   
327         bh.len= len;
328         
329         mywrite(wd, &bh, sizeof(BHead));
330         if(len) mywrite(wd, adr, len);
331 }
332
333 static void write_scriptlink(WriteData *wd, ScriptLink *slink)
334 {
335         writedata(wd, DATA, sizeof(void *)*slink->totscript, slink->scripts);   
336         writedata(wd, DATA, sizeof(short)*slink->totscript, slink->flag);       
337 }
338
339 static void write_renderinfo(WriteData *wd)             /* for renderdaemon */
340 {
341         Scene *sce;
342         int data[8];
343         
344         sce= G.main->scene.first;
345         while(sce) {
346                 if(sce->id.lib==0  && ( sce==G.scene || (sce->r.scemode & R_BG_RENDER)) ) {
347                         data[0]= sce->r.sfra;
348                         data[1]= sce->r.efra;
349                         
350                         strncpy((char *)(data+2), sce->id.name+2, 23);
351                         
352                         writedata(wd, REND, 32, data);
353                 }
354                 sce= sce->id.next;
355         }
356 }
357
358 static void write_userdef(WriteData *wd)
359 {
360         bTheme *btheme;
361         
362         writestruct(wd, USER, "UserDef", 1, &U);
363         
364         btheme= U.themes.first;
365         while(btheme) {
366                 writestruct(wd, DATA, "bTheme", 1, btheme);
367                 btheme= btheme->next;
368         }
369 }
370
371 static void write_effects(WriteData *wd, ListBase *lb)
372 {
373         Effect *eff;
374         
375         eff= lb->first;
376         while(eff) {
377                 
378                 switch(eff->type) {
379                 case EFF_BUILD:
380                         writestruct(wd, DATA, "BuildEff", 1, eff);
381                         break;  
382                 case EFF_PARTICLE:
383                         writestruct(wd, DATA, "PartEff", 1, eff);
384                         break;  
385                 case EFF_WAVE:
386                         writestruct(wd, DATA, "WaveEff", 1, eff);
387                         break;  
388                 default:
389                         writedata(wd, DATA, MEM_allocN_len(eff), eff);
390                 }
391                 
392                 eff= eff->next;
393         }
394 }
395
396 static void write_properties(WriteData *wd, ListBase *lb)
397 {
398         bProperty *prop;
399         
400         prop= lb->first;
401         while(prop) {
402                 writestruct(wd, DATA, "bProperty", 1, prop);
403         
404                 if(prop->poin && prop->poin != &prop->data) 
405                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
406         
407                 prop= prop->next;
408         }
409 }
410
411 static void write_sensors(WriteData *wd, ListBase *lb)
412 {
413         bSensor *sens;
414         
415         sens= lb->first;
416         while(sens) {
417                 writestruct(wd, DATA, "bSensor", 1, sens);
418                 
419                 writedata(wd, DATA, sizeof(void *)*sens->totlinks, sens->links);
420                 
421                 switch(sens->type) {
422                 case SENS_NEAR:
423                         writestruct(wd, DATA, "bNearSensor", 1, sens->data);
424                         break;
425                 case SENS_MOUSE:
426                         writestruct(wd, DATA, "bMouseSensor", 1, sens->data);
427                         break;
428                 case SENS_TOUCH:
429                         writestruct(wd, DATA, "bTouchSensor", 1, sens->data);
430                         break;
431                 case SENS_KEYBOARD:
432                         writestruct(wd, DATA, "bKeyboardSensor", 1, sens->data);
433                         break;
434                 case SENS_PROPERTY:
435                         writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
436                         break;
437                 case SENS_COLLISION:
438                         writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
439                         break;
440                 case SENS_RADAR:
441                         writestruct(wd, DATA, "bRadarSensor", 1, sens->data);
442                         break;
443                 case SENS_RANDOM:
444                         writestruct(wd, DATA, "bRandomSensor", 1, sens->data);
445                         break;
446                 case SENS_RAY:
447                         writestruct(wd, DATA, "bRaySensor", 1, sens->data);
448                         break;
449                 case SENS_MESSAGE:
450                         writestruct(wd, DATA, "bMessageSensor", 1, sens->data);
451                         break;
452                 default:
453                         ; /* error: don't know how to write this file */
454                 }
455         
456                 sens= sens->next;
457         }
458 }
459
460 static void write_controllers(WriteData *wd, ListBase *lb)
461 {
462         bController *cont;
463         
464         cont= lb->first;
465         while(cont) {
466                 writestruct(wd, DATA, "bController", 1, cont);
467         
468                 writedata(wd, DATA, sizeof(void *)*cont->totlinks, cont->links);
469         
470                 switch(cont->type) {
471                 case CONT_EXPRESSION:
472                         writestruct(wd, DATA, "bExpressionCont", 1, cont->data);
473                         break;
474                 case CONT_PYTHON:
475                         writestruct(wd, DATA, "bPythonCont", 1, cont->data);
476                         break;
477                 default:
478                         ; /* error: don't know how to write this file */
479                 }
480         
481                 cont= cont->next;
482         }
483 }
484
485 static void write_actuators(WriteData *wd, ListBase *lb)
486 {
487         bActuator *act;
488         
489         act= lb->first;
490         while(act) {
491                 writestruct(wd, DATA, "bActuator", 1, act);
492         
493                 switch(act->type) {
494                 case ACT_ACTION:
495                         writestruct(wd, DATA, "bActionActuator", 1, act->data);
496                         break;
497                 case ACT_SOUND:
498                         writestruct(wd, DATA, "bSoundActuator", 1, act->data);
499                         break;
500                 case ACT_CD:
501                         writestruct(wd, DATA, "bCDActuator", 1, act->data);
502                         break;
503                 case ACT_OBJECT:
504                         writestruct(wd, DATA, "bObjectActuator", 1, act->data);
505                         break;
506                 case ACT_IPO:
507                         writestruct(wd, DATA, "bIpoActuator", 1, act->data);
508                         break;
509                 case ACT_PROPERTY:
510                         writestruct(wd, DATA, "bPropertyActuator", 1, act->data);
511                         break;
512                 case ACT_CAMERA:
513                         writestruct(wd, DATA, "bCameraActuator", 1, act->data);
514                         break;
515                 case ACT_CONSTRAINT:
516                         writestruct(wd, DATA, "bConstraintActuator", 1, act->data);
517                         break;
518                 case ACT_EDIT_OBJECT:
519                         writestruct(wd, DATA, "bEditObjectActuator", 1, act->data);
520                         break;
521                 case ACT_SCENE:
522                         writestruct(wd, DATA, "bSceneActuator", 1, act->data);
523                         break;
524                 case ACT_GROUP:
525                         writestruct(wd, DATA, "bGroupActuator", 1, act->data);
526                         break;
527                 case ACT_RANDOM:
528                         writestruct(wd, DATA, "bRandomActuator", 1, act->data);
529                         break;
530                 case ACT_MESSAGE:
531                         writestruct(wd, DATA, "bMessageActuator", 1, act->data);
532                         break;
533                 case ACT_GAME:
534                         writestruct(wd, DATA, "bGameActuator", 1, act->data);
535                         break;
536                 case ACT_VISIBILITY:
537                         writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
538                         break;
539                 default:
540                         ; /* error: don't know how to write this file */
541                 }
542         
543                 act= act->next;
544         }
545 }
546
547 static void write_nlastrips(WriteData *wd, ListBase *nlabase)
548 {
549         bActionStrip *strip;
550
551         for (strip=nlabase->first; strip; strip=strip->next)
552                 writestruct(wd, DATA, "bActionStrip", 1, strip);
553 }
554
555 static void write_constraints(WriteData *wd, ListBase *conlist)
556 {
557         bConstraint *con;
558         
559         for (con=conlist->first; con; con=con->next) {
560                 /* Write the specific data */
561                 switch (con->type) {
562                 case CONSTRAINT_TYPE_NULL:
563                         break;
564                 case CONSTRAINT_TYPE_TRACKTO:
565                         writestruct(wd, DATA, "bTrackToConstraint", 1, con->data);
566                         break;
567                 case CONSTRAINT_TYPE_KINEMATIC:
568                         writestruct(wd, DATA, "bKinematicConstraint", 1, con->data);
569                         break;
570                 case CONSTRAINT_TYPE_ROTLIKE:
571                         writestruct(wd, DATA, "bRotateLikeConstraint", 1, con->data);
572                         break;
573                 case CONSTRAINT_TYPE_LOCLIKE:
574                         writestruct(wd, DATA, "bLocateLikeConstraint", 1, con->data);
575                         break;
576                 case CONSTRAINT_TYPE_ACTION:
577                         writestruct(wd, DATA, "bActionConstraint", 1, con->data);
578                         break;
579                 case CONSTRAINT_TYPE_LOCKTRACK:
580                         writestruct(wd, DATA, "bLockTrackConstraint", 1, con->data);
581                         break;
582                 case CONSTRAINT_TYPE_FOLLOWPATH:
583                         writestruct(wd, DATA, "bFollowPathConstraint", 1, con->data);
584                         break;
585                 default:
586                         break;
587                 }
588                 /* Write the constraint */
589                 writestruct(wd, DATA, "bConstraint", 1, con);
590         }
591 }
592
593 static void write_pose(WriteData *wd, bPose *pose)
594 {
595         bPoseChannel    *chan;
596         
597         /* Write each channel */
598         
599         if (!pose)
600                 return;
601         
602         // Write channels
603         for (chan=pose->chanbase.first; chan; chan=chan->next) {
604                 write_constraints(wd, &chan->constraints);
605                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
606         }
607         
608         // Write this pose 
609         writestruct(wd, DATA, "bPose", 1, pose);
610 }
611
612 static void write_defgroups(WriteData *wd, ListBase *defbase)
613 {
614         bDeformGroup    *defgroup;
615         
616         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
617                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
618 }
619
620 static void write_constraint_channels(WriteData *wd, ListBase *chanbase)
621 {
622         bConstraintChannel *chan;
623
624         for (chan = chanbase->first; chan; chan=chan->next)
625                 writestruct(wd, DATA, "bConstraintChannel", 1, chan);
626         
627 }
628
629 static void write_objects(WriteData *wd, ListBase *idbase)
630 {
631         Object *ob;
632         
633         ob= idbase->first;
634         while(ob) {
635                 if(ob->id.us>0) {
636                         /* write LibData */
637                         writestruct(wd, ID_OB, "Object", 1, ob);
638                         
639                         /* direct data */
640                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
641                         write_effects(wd, &ob->effect);
642                         write_properties(wd, &ob->prop);
643                         write_sensors(wd, &ob->sensors);
644                         write_controllers(wd, &ob->controllers);
645                         write_actuators(wd, &ob->actuators);
646                         write_scriptlink(wd, &ob->scriptlink);
647                         write_pose(wd, ob->pose);
648                         write_defgroups(wd, &ob->defbase);
649                         write_constraints(wd, &ob->constraints);
650                         write_constraint_channels(wd, &ob->constraintChannels);
651                         write_nlastrips(wd, &ob->nlastrips);
652                 }
653                 ob= ob->id.next;
654         }
655 }
656
657
658 static void write_vfonts(WriteData *wd, ListBase *idbase)
659 {
660         VFont *vf;
661         PackedFile * pf;
662         
663         vf= idbase->first;
664         while(vf) {
665                 if(vf->id.us>0) {
666                         /* write LibData */
667                         writestruct(wd, ID_VF, "VFont", 1, vf);
668                 
669                         /* direct data */
670                         
671                         if (vf->packedfile) {
672                                 pf = vf->packedfile;
673                                 writestruct(wd, DATA, "PackedFile", 1, pf);
674                                 writedata(wd, DATA, pf->size, pf->data);
675                         }
676                 }
677                 
678                 vf= vf->id.next;
679         }
680 }
681
682 static void write_ipos(WriteData *wd, ListBase *idbase)
683 {
684         Ipo *ipo;
685         IpoCurve *icu;
686         
687         ipo= idbase->first;
688         while(ipo) {
689                 if(ipo->id.us>0) {
690                         /* write LibData */
691                         writestruct(wd, ID_IP, "Ipo", 1, ipo);
692                 
693                         /* direct data */
694                         icu= ipo->curve.first;
695                         while(icu) {
696                                 writestruct(wd, DATA, "IpoCurve", 1, icu);
697                                 icu= icu->next;
698                         }
699         
700                         icu= ipo->curve.first;
701                         while(icu) {
702                                 if(icu->bezt)  writestruct(wd, DATA, "BezTriple", icu->totvert, icu->bezt);
703                                 if(icu->bp)  writestruct(wd, DATA, "BPoint", icu->totvert, icu->bp);
704                                 icu= icu->next;
705                         }
706                 }
707                 
708                 ipo= ipo->id.next;
709         }
710 }
711
712 static void write_keys(WriteData *wd, ListBase *idbase)
713 {
714         Key *key;
715         KeyBlock *kb;
716         
717         key= idbase->first;
718         while(key) {
719                 if(key->id.us>0) {
720                         /* write LibData */
721                         writestruct(wd, ID_KE, "Key", 1, key);
722                 
723                         /* direct data */
724                         kb= key->block.first;
725                         while(kb) {
726                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
727                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
728                                 kb= kb->next;
729                         }
730                 }
731                 
732                 key= key->id.next;
733         }
734 }
735
736 static void write_cameras(WriteData *wd, ListBase *idbase)
737 {
738         Camera *cam;
739         
740         cam= idbase->first;
741         while(cam) {
742                 if(cam->id.us>0) {
743                         /* write LibData */
744                         writestruct(wd, ID_CA, "Camera", 1, cam);
745                 
746                         /* direct data */
747                         write_scriptlink(wd, &cam->scriptlink);
748                 }
749                 
750                 cam= cam->id.next;
751         }
752 }
753
754 static void write_mballs(WriteData *wd, ListBase *idbase)
755 {
756         MetaBall *mb;
757         MetaElem *ml;
758         
759         mb= idbase->first;
760         while(mb) {
761                 if(mb->id.us>0) {
762                         /* write LibData */
763                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
764                         
765                         /* direct data */
766                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
767                         
768                         ml= mb->elems.first;
769                         while(ml) {
770                                 writestruct(wd, DATA, "MetaElem", 1, ml);
771                                 ml= ml->next;
772                         }
773                 }
774                 mb= mb->id.next;
775         }
776 }
777
778 static void write_curves(WriteData *wd, ListBase *idbase)
779 {
780         Curve *cu;
781         Nurb *nu;
782         
783         cu= idbase->first;
784         while(cu) {
785                 if(cu->id.us>0) {
786                         /* write LibData */
787                         writestruct(wd, ID_CU, "Curve", 1, cu);
788                         
789                         /* direct data */
790                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
791                         
792                         if(cu->vfont) {
793                                 writedata(wd, DATA, cu->len+1, cu->str);
794                         }
795                         else {
796                                 /* is also the order of reading */
797                                 nu= cu->nurb.first;
798                                 while(nu) {
799                                         writestruct(wd, DATA, "Nurb", 1, nu);
800                                         nu= nu->next;
801                                 }
802                                 nu= cu->nurb.first;
803                                 while(nu) {
804                                         if( (nu->type & 7)==CU_BEZIER) 
805                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
806                                         else {
807                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
808                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
809                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
810                                         }
811                                         nu= nu->next;
812                                 }
813                         }
814                 }
815                 cu= cu->id.next;
816         }
817 }
818
819 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
820 {
821         int     i;
822                 
823         /* Write the dvert list */
824         writestruct(wd, DATA, "MDeformVert", count, dvlist);
825         
826         /* Write deformation data for each dvert */
827         if (dvlist) {
828                 for (i=0; i<count; i++) {
829                         if (dvlist[i].dw)
830                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw); 
831                 }
832         }
833 }
834
835 static void write_meshs(WriteData *wd, ListBase *idbase)
836 {
837         Mesh *mesh;
838         
839         mesh= idbase->first;
840         while(mesh) {
841                 if(mesh->id.us>0) {
842                         /* write LibData */
843                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
844                         
845                         /* direct data */
846                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
847                         writestruct(wd, DATA, "MVert", mesh->totvert, mesh->mvert);
848                         write_dverts(wd, mesh->totvert, mesh->dvert);
849                         writestruct(wd, DATA, "MFace", mesh->totface, mesh->mface);
850                         writestruct(wd, DATA, "TFace", mesh->totface, mesh->tface);
851                         writestruct(wd, DATA, "MCol", 4*mesh->totface, mesh->mcol);
852                         writestruct(wd, DATA, "MSticky", mesh->totvert, mesh->msticky);
853         
854                 }
855                 mesh= mesh->id.next;
856         }
857 }
858
859 static void write_images(WriteData *wd, ListBase *idbase)
860 {
861         Image *ima;
862         PackedFile * pf;
863         
864         ima= idbase->first;
865         while(ima) {
866                 if(ima->id.us>0) {
867                         /* write LibData */
868                         writestruct(wd, ID_IM, "Image", 1, ima);
869         
870                         if (ima->packedfile) {
871                                 pf = ima->packedfile;
872                                 writestruct(wd, DATA, "PackedFile", 1, pf);
873                                 writedata(wd, DATA, pf->size, pf->data);
874                         }
875                 }
876                 ima= ima->id.next;
877         }
878 }
879
880 static void write_textures(WriteData *wd, ListBase *idbase)
881 {
882         Tex *tex;
883         
884         tex= idbase->first;
885         while(tex) {
886                 if(tex->id.us>0) {
887                         /* write LibData */
888                         writestruct(wd, ID_TE, "Tex", 1, tex);
889                         
890                         /* direct data */
891                         if(tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
892                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
893                         if(tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
894                 }
895                 tex= tex->id.next;
896         }
897 }
898
899 static void write_materials(WriteData *wd, ListBase *idbase)
900 {
901         Material *ma;
902         int a;
903         
904         ma= idbase->first;
905         while(ma) {
906                 if(ma->id.us>0) {
907                         /* write LibData */
908                         writestruct(wd, ID_MA, "Material", 1, ma);
909                         
910                         for(a=0; a<8; a++) {
911                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
912                         }
913         
914                         write_scriptlink(wd, &ma->scriptlink);
915                 }
916                 ma= ma->id.next;
917         }
918 }
919
920 static void write_worlds(WriteData *wd, ListBase *idbase)
921 {
922         World *wrld;
923         int a;
924         
925         wrld= idbase->first;
926         while(wrld) {
927                 if(wrld->id.us>0) {
928                         /* write LibData */
929                         writestruct(wd, ID_WO, "World", 1, wrld);
930         
931                         for(a=0; a<8; a++) {
932                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
933                         }
934         
935                         write_scriptlink(wd, &wrld->scriptlink);
936                 }
937                 wrld= wrld->id.next;
938         }
939 }
940
941 static void write_lamps(WriteData *wd, ListBase *idbase)
942 {
943         Lamp *la;
944         int a;
945         
946         la= idbase->first;
947         while(la) {
948                 if(la->id.us>0) {
949                         /* write LibData */
950                         writestruct(wd, ID_LA, "Lamp", 1, la);
951                 
952                         /* direct data */
953                         for(a=0; a<8; a++) {
954                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
955                         }
956         
957                         write_scriptlink(wd, &la->scriptlink);
958                 }
959                 la= la->id.next;
960         }
961 }
962
963 static void write_lattices(WriteData *wd, ListBase *idbase)
964 {
965         Lattice *lt;
966         
967         lt= idbase->first;
968         while(lt) {
969                 if(lt->id.us>0) {
970                         /* write LibData */
971                         writestruct(wd, ID_LT, "Lattice", 1, lt);
972                 
973                         /* direct data */
974                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
975                 }
976                 lt= lt->id.next;
977         }
978 }
979
980 static void write_ikas(WriteData *wd, ListBase *idbase)
981 {
982         Ika *ika;
983         Limb *li;
984         
985         ika= idbase->first;
986         while(ika) {
987                 if(ika->id.us>0) {
988                         /* write LibData */
989                         writestruct(wd, ID_IK, "Ika", 1, ika);
990                         
991                         /* direct data */
992                         li= ika->limbbase.first;
993                         while(li) {
994                                 writestruct(wd, DATA, "Limb", 1, li);
995                                 li= li->next;
996                         }
997                         
998                         writestruct(wd, DATA, "Deform", ika->totdef, ika->def);
999                 }
1000                 ika= ika->id.next;
1001         }
1002 }
1003
1004 static void write_scenes(WriteData *wd, ListBase *scebase)
1005 {
1006         Scene *sce;
1007         Base *base;
1008         Editing *ed;
1009         Sequence *seq;
1010         Strip *strip;
1011         
1012         sce= scebase->first;
1013         while(sce) {
1014                 /* write LibData */
1015                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1016                 
1017                 /* direct data */
1018                 base= sce->base.first;
1019                 while(base) {
1020                         writestruct(wd, DATA, "Base", 1, base);
1021                         base= base->next;
1022                 }
1023                 
1024                 writestruct(wd, DATA, "Radio", 1, sce->radio);
1025                 writestruct(wd, DATA, "FreeCamera", 1, sce->fcam);
1026                 
1027                 ed= sce->ed;
1028                 if(ed) {
1029                         writestruct(wd, DATA, "Editing", 1, ed);
1030         
1031                         /* reset write flags too */
1032                         WHILE_SEQ(&ed->seqbase) {
1033                                 if(seq->strip) seq->strip->done= 0;
1034                                 writestruct(wd, DATA, "Sequence", 1, seq);
1035                         }
1036                         END_SEQ
1037                         
1038                         WHILE_SEQ(&ed->seqbase) {
1039                                 if(seq->strip && seq->strip->done==0) {
1040                                         /* write strip with 'done' at 0 because readfile */
1041                                         
1042                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1043                                         
1044                                         strip= seq->strip;
1045                                         writestruct(wd, DATA, "Strip", 1, strip);
1046                                         
1047                                         if(seq->type==SEQ_IMAGE) 
1048                                                 writestruct(wd, DATA, "StripElem", strip->len, strip->stripdata);
1049                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_SOUND)
1050                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1051                                                 
1052                                         strip->done= 1;
1053                                 }
1054                         }
1055                         END_SEQ
1056                 }
1057         
1058                 write_scriptlink(wd, &sce->scriptlink);
1059
1060                 if (sce->r.avicodecdata) {
1061                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1062                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1063                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1064                 }
1065                 
1066                 if (sce->r.qtcodecdata) {
1067                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1068                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1069                 }
1070
1071                 sce= sce->id.next;
1072         }
1073 }
1074
1075 static void write_screens(WriteData *wd, ListBase *scrbase)
1076 {
1077         bScreen *sc;
1078         ScrArea *sa;
1079         ScrVert *sv;
1080         ScrEdge *se;
1081         
1082         sc= scrbase->first;
1083         while(sc) {
1084                 /* write LibData */
1085                 writestruct(wd, ID_SCR, "Screen", 1, sc);
1086                 
1087                 /* direct data */
1088                 sv= sc->vertbase.first;
1089                 while(sv) {
1090                         writestruct(wd, DATA, "ScrVert", 1, sv);
1091                         sv= sv->next;
1092                 }
1093         
1094                 se= sc->edgebase.first;
1095                 while(se) {
1096                         writestruct(wd, DATA, "ScrEdge", 1, se);
1097                         se= se->next;
1098                 }
1099         
1100                 sa= sc->areabase.first;
1101                 while(sa) {
1102                         SpaceLink *sl;
1103                         Panel *pa;
1104
1105                         writestruct(wd, DATA, "ScrArea", 1, sa);
1106                         
1107                         pa= sa->panels.first;
1108                         while(pa) {
1109                                 writestruct(wd, DATA, "Panel", 1, pa);
1110                                 pa= pa->next;
1111                         }
1112                         
1113                         sl= sa->spacedata.first;
1114                         while(sl) {
1115                                 if(sl->spacetype==SPACE_VIEW3D) {
1116                                         View3D *v3d= (View3D*) sl;
1117                                         writestruct(wd, DATA, "View3D", 1, v3d);
1118                                         if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
1119                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
1120                                 }
1121                                 else if(sl->spacetype==SPACE_IPO) {
1122                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
1123                                 }
1124                                 else if(sl->spacetype==SPACE_BUTS) {
1125                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
1126                                 }
1127                                 else if(sl->spacetype==SPACE_FILE) {
1128                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
1129                                 }
1130                                 else if(sl->spacetype==SPACE_SEQ) {
1131                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
1132                                 }
1133                                 else if(sl->spacetype==SPACE_OOPS) {
1134                                         SpaceOops *so= (SpaceOops *)sl;
1135                                         Oops *oops;
1136                                         
1137                                         /* cleanup */
1138                                         oops= so->oops.first;
1139                                         while(oops) {
1140                                                 Oops *oopsn= oops->next;
1141                                                 if(oops->id==0) {
1142                                                         BLI_remlink(&so->oops, oops);
1143                                                         free_oops(oops);
1144                                                 }
1145                                                 oops= oopsn;
1146                                         }
1147         
1148                                         /* ater cleanup, because of listbase! */
1149                                         writestruct(wd, DATA, "SpaceOops", 1, so);
1150         
1151                                         oops= so->oops.first;
1152                                         while(oops) {
1153                                                 writestruct(wd, DATA, "Oops", 1, oops);
1154                                                 oops= oops->next;
1155                                         }
1156                                 }
1157                                 else if(sl->spacetype==SPACE_IMAGE) {
1158                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
1159                                 }
1160                                 else if(sl->spacetype==SPACE_IMASEL) {
1161                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
1162                                 }
1163                                 else if(sl->spacetype==SPACE_TEXT) {
1164                                         writestruct(wd, DATA, "SpaceText", 1, sl);
1165                                 }
1166                                 else if(sl->spacetype==SPACE_SCRIPT) {
1167                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
1168                                 }
1169                                 else if(sl->spacetype==SPACE_ACTION) {
1170                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
1171                                 }
1172                                 else if(sl->spacetype==SPACE_SOUND) {
1173                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
1174                                 }
1175                                 else if(sl->spacetype==SPACE_NLA){
1176                                         writestruct(wd, DATA, "SpaceNla", 1, sl);
1177                                 }
1178                                 sl= sl->next;
1179                         }
1180                         
1181                         sa= sa->next;
1182                 }
1183         
1184                 sc= sc->id.next;
1185         }
1186 }
1187
1188 static void write_libraries(WriteData *wd, Main *main)
1189 {
1190         ListBase *lbarray[30];
1191         ID *id;
1192         int a, tot, foundone;
1193         
1194         while(main) {
1195         
1196                 a=tot= set_listbasepointers(main, lbarray);
1197         
1198                 /* test: is lib being used */
1199                 foundone= 0;
1200                 while(tot--) {
1201                         id= lbarray[tot]->first;
1202                         while(id) {
1203                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
1204                                         foundone= 1;
1205                                         break;
1206                                 }
1207                                 id= id->next;
1208                         }
1209                         if(foundone) break;
1210                 }
1211                 
1212                 if(foundone) {  
1213                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
1214         
1215                         while(a--) {
1216                                 id= lbarray[a]->first;
1217                                 while(id) {
1218                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
1219                                                 
1220                                                 writestruct(wd, ID_ID, "ID", 1, id);
1221                                         }
1222                                         id= id->next;
1223                                 }
1224                         }
1225                 }
1226                 
1227                 main= main->next;
1228         }
1229 }
1230
1231 static void write_bone(WriteData *wd, Bone* bone)
1232 {
1233         Bone*   cbone;
1234         
1235 //      write_constraints(wd, &bone->constraints);      
1236         
1237         // Write this bone 
1238         writestruct(wd, DATA, "Bone", 1, bone);
1239         
1240         // Write Children 
1241         cbone= bone->childbase.first;
1242         while(cbone) {
1243                 write_bone(wd, cbone);
1244                 cbone= cbone->next;
1245         }
1246 }
1247
1248 static void write_armatures(WriteData *wd, ListBase *idbase)
1249 {
1250         bArmature       *arm;
1251         Bone            *bone;
1252         
1253         arm=idbase->first;
1254         while (arm) {
1255                 if (arm->id.us>0) {
1256                         writestruct(wd, ID_AR, "bArmature", 1, arm);
1257         
1258                         /* Direct data */
1259                         bone= arm->bonebase.first;
1260                         while(bone) {
1261                                 write_bone(wd, bone);
1262                                 bone=bone->next;
1263                         }
1264                 }
1265                 arm=arm->id.next;
1266         }
1267 }
1268
1269 static void write_actions(WriteData *wd, ListBase *idbase)
1270 {
1271         bAction                 *act;
1272         bActionChannel  *chan;
1273         act=idbase->first;
1274         while (act) {
1275                 if (act->id.us>0) {
1276                         writestruct(wd, ID_AC, "bAction", 1, act);
1277                         
1278                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1279                                 writestruct(wd, DATA, "bActionChannel", 1, chan);
1280                                 write_constraint_channels(wd, &chan->constraintChannels);
1281                         }
1282                 }
1283                 act=act->id.next;
1284         }
1285 }
1286
1287 static void write_texts(WriteData *wd, ListBase *idbase)
1288 {
1289         Text *text;
1290         TextLine *tmp;
1291         
1292         text= idbase->first;
1293         while(text) {
1294                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
1295                 
1296                 /* write LibData */
1297                 writestruct(wd, ID_TXT, "Text", 1, text);
1298                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
1299         
1300                 if(!(text->flags & TXT_ISEXT)) {                        
1301                         /* now write the text data, in two steps for optimization in the readfunction */
1302                         tmp= text->lines.first;
1303                         while (tmp) {
1304                                 writestruct(wd, DATA, "TextLine", 1, tmp);
1305                                 tmp= tmp->next;
1306                         }
1307         
1308                         tmp= text->lines.first;
1309                         while (tmp) {
1310                                 writedata(wd, DATA, tmp->len+1, tmp->line);
1311                                 tmp= tmp->next;
1312                         }
1313                 }
1314                 text= text->id.next;
1315         }
1316 }
1317
1318 static void write_sounds(WriteData *wd, ListBase *idbase)
1319 {
1320         bSound *sound;
1321         bSample *sample;
1322         
1323         PackedFile * pf;
1324         
1325         // set all samples to unsaved status
1326         
1327         sample = samples->first;
1328         while (sample) {
1329                 sample->flags |= SAMPLE_NEEDS_SAVE;
1330                 sample = sample->id.next;
1331         }
1332         
1333         sound= idbase->first;
1334         while(sound) {
1335                 if(sound->id.us>0) {
1336                         // do we need to save the packedfile as well ?
1337                         sample = sound->sample;
1338                         if (sample) {
1339                                 if (sample->flags & SAMPLE_NEEDS_SAVE) {
1340                                         sound->newpackedfile = sample->packedfile;
1341                                         sample->flags &= ~SAMPLE_NEEDS_SAVE;
1342                                 } else {
1343                                         sound->newpackedfile = NULL;
1344                                 }
1345                         }
1346         
1347                         /* write LibData */
1348                         writestruct(wd, ID_SO, "bSound", 1, sound);
1349         
1350                         if (sound->newpackedfile) {
1351                                 pf = sound->newpackedfile;
1352                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1353                                 writedata(wd, DATA, pf->size, pf->data);
1354                         }
1355         
1356                         if (sample) {
1357                                 sound->newpackedfile = sample->packedfile;
1358                         }
1359                 }
1360                 sound= sound->id.next;
1361         }
1362 }
1363
1364 static void write_groups(WriteData *wd, ListBase *idbase)
1365 {
1366         Group *group;
1367         GroupKey *gk;
1368         GroupObject *go;
1369         ObjectKey *ok;
1370         
1371         group= idbase->first;
1372         while(group) {
1373                 if(group->id.us>0) {
1374                         /* write LibData */
1375                         writestruct(wd, ID_GR, "Group", 1, group);
1376                         
1377                         gk= group->gkey.first;
1378                         while(gk) {
1379                                 writestruct(wd, DATA, "GroupKey", 1, gk);
1380                                 gk= gk->next;
1381                         }
1382         
1383                         go= group->gobject.first;
1384                         while(go) {
1385                                 writestruct(wd, DATA, "GroupObject", 1, go);
1386                                 go= go->next;
1387                         }
1388                         go= group->gobject.first;
1389                         while(go) {
1390                                 ok= go->okey.first;
1391                                 while(ok) {
1392                                         writestruct(wd, DATA, "ObjectKey", 1, ok);
1393                                         ok= ok->next;
1394                                 }
1395                                 go= go->next;
1396                         }
1397                         
1398                 }
1399                 group= group->id.next;
1400         }
1401 }
1402
1403 static void write_global(WriteData *wd)
1404 {
1405         FileGlobal fg;
1406         
1407         fg.curscreen= G.curscreen;
1408         fg.displaymode= R.displaymode;
1409         fg.winpos= R.winpos;
1410         fg.fileflags= G.fileflags;
1411         fg.globalf= G.f;
1412         
1413         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
1414 }
1415
1416 static int write_file_handle(int handle, int write_user_block, int write_flags) 
1417 {
1418         ListBase mainlist;
1419         char buf[13];
1420         WriteData *wd;
1421         int data;
1422         
1423         mainlist.first= mainlist.last= G.main;
1424         G.main->next= NULL;
1425         
1426         blo_split_main(&mainlist);
1427         
1428         wd= bgnwrite(handle, write_flags);
1429
1430         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (G.order==B_ENDIAN)?'V':'v', G.version);
1431         mywrite(wd, buf, 12);
1432         
1433         write_renderinfo(wd);
1434         
1435         write_screens  (wd, &G.main->screen);
1436         write_scenes   (wd, &G.main->scene);
1437         write_objects  (wd, &G.main->object);
1438         write_meshs    (wd, &G.main->mesh);
1439         write_curves   (wd, &G.main->curve);
1440         write_mballs   (wd, &G.main->mball);
1441         write_materials(wd, &G.main->mat);
1442         write_textures (wd, &G.main->tex);
1443         write_images   (wd, &G.main->image);
1444         write_cameras  (wd, &G.main->camera);
1445         write_lamps    (wd, &G.main->lamp);
1446         write_lattices (wd, &G.main->latt);
1447         write_ikas     (wd, &G.main->ika);
1448         write_vfonts   (wd, &G.main->vfont);
1449         write_ipos     (wd, &G.main->ipo);
1450         write_keys     (wd, &G.main->key);
1451         write_worlds   (wd, &G.main->world);
1452         write_texts    (wd, &G.main->text);
1453         write_sounds   (wd, &G.main->sound);
1454         write_groups   (wd, &G.main->group);
1455         write_armatures(wd, &G.main->armature);
1456         write_actions  (wd, &G.main->action);
1457         write_libraries(wd,  G.main->next);
1458
1459         write_global(wd);
1460         if (write_user_block) {
1461                 write_userdef(wd);
1462         }
1463         
1464         /* dna as last, because (to be implemented) test for which structs are written */
1465         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
1466         
1467         data= ENDB;
1468         mywrite(wd, &data, 4);
1469         
1470         data= 0;
1471         mywrite(wd, &data, 4);
1472         
1473         blo_join_main(&mainlist);
1474         G.main= mainlist.first;
1475         
1476         return endwrite(wd);
1477 }
1478
1479 int BLO_write_file(char *dir, int write_flags, char **error_r)
1480 {
1481         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
1482         char tempname[FILE_MAXDIR+FILE_MAXFILE];
1483         int file, fout, write_user_block;
1484 #ifdef WIN32
1485         char tmpdir[FILE_MAXDIR+FILE_MAXFILE];
1486 #endif
1487         
1488         sprintf(tempname, "%s@", dir);
1489
1490         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
1491         if(file == -1) {
1492                 *error_r= "Unable to open";
1493                 return 0;
1494         }
1495         
1496 #if 0
1497         BLI_getInstallationDir(tmpdir);
1498
1499         if(BLI_exists(tmpdir))
1500                 strcat(tmpdir,"/.blender/");
1501
1502         BLI_make_file_string(G.sce, userfilename, tmpdir, ".B.blend");
1503 #else
1504         BLI_make_file_string(G.sce, userfilename, BLI_gethome(), ".B.blend");
1505 #endif
1506
1507         write_user_block= BLI_streq(dir, userfilename);
1508
1509         fout= write_file_handle(file, write_user_block, write_flags);
1510         close(file);
1511         
1512         if(!fout) {
1513                 if(BLI_rename(tempname, dir) < 0) {
1514                         *error_r= "Can't change old file. File saved with @";
1515                         return 0;
1516                 }
1517         } else {
1518                 remove(tempname);
1519
1520                 *error_r= "Not enough diskspace";
1521                 return 0;
1522         }
1523         
1524         return 1;
1525 }
1526
1527         /* Runtime writing */
1528
1529 #ifdef WIN32
1530 #define PATHSEPERATOR           "\\"
1531 #else
1532 #define PATHSEPERATOR           "/"
1533 #endif  
1534
1535 static char *get_install_dir(void) {
1536         extern char bprogname[];
1537         char *tmpname = BLI_strdup(bprogname);
1538         char *cut;
1539
1540 #ifdef __APPLE__
1541         cut = strstr(tmpname, ".app");
1542         if (cut) cut[0] = 0;
1543 #endif
1544
1545         cut = BLI_last_slash(tmpname);
1546         
1547         if (cut) {
1548                 cut[0] = 0;
1549                 return tmpname;
1550         } else {
1551                 MEM_freeN(tmpname);
1552                 return NULL;
1553         }
1554 }
1555
1556 static char *get_runtime_path(char *exename) {
1557         char *installpath= get_install_dir();
1558         
1559         if (!installpath) {
1560                 return NULL;
1561         } else {
1562                 char *path= MEM_mallocN(strlen(installpath)+strlen(PATHSEPERATOR)+strlen(exename)+1, "runtimepath");
1563                 strcpy(path, installpath);
1564                 strcat(path, PATHSEPERATOR);
1565                 strcat(path, exename);
1566         
1567                 MEM_freeN(installpath);
1568         
1569                 return path;
1570         }
1571 }
1572
1573 #ifdef __APPLE__
1574
1575 static int recursive_copy_runtime(char *outname, char *exename, char **cause_r) {
1576         char *cause = NULL, *runtime = get_runtime_path(exename);
1577         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
1578         int progfd = -1;
1579         
1580         if (!runtime) {
1581                 cause= "Unable to find runtime";
1582                 goto cleanup;
1583         }
1584         
1585         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
1586         if (progfd==-1) {
1587                 cause= "Unable to find runtime";
1588                 goto cleanup;
1589         }
1590
1591         sprintf(command, "/bin/cp -R %s %s", runtime, outname);
1592         if (system(command) == -1) {
1593                 cause = "Couldn't copy runtime";
1594         }
1595
1596 cleanup:
1597         if (progfd!=-1)
1598                 close(progfd);
1599         if (runtime)
1600                 MEM_freeN(runtime);
1601         
1602         if (cause) {
1603                 *cause_r= cause;
1604                 return 0;
1605         } else
1606                 return 1;
1607 }
1608
1609 void BLO_write_runtime(char *file, char *exename) {
1610         char gamename[FILE_MAXDIR+FILE_MAXFILE];
1611         int outfd = -1;
1612         char *cause= NULL;
1613         
1614         // remove existing file / bundle
1615         BLI_delete(file, NULL, TRUE);
1616         
1617         if (!recursive_copy_runtime(file, exename, &cause))
1618                 goto cleanup;
1619                 
1620         strcpy(gamename, file);
1621         strcat(gamename, "/Contents/Resources/game.blend");
1622         
1623         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
1624         if (outfd != -1) {
1625
1626                 write_file_handle(outfd, 0, G.fileflags);
1627                 
1628                 if (write(outfd, " ", 1) != 1) {
1629                         cause= "Unable to write to output file";
1630                         goto cleanup;
1631                 }
1632         } else {
1633                 cause = "Unable to open blenderfile";
1634         }
1635         
1636 cleanup:
1637         if (outfd!=-1)
1638                 close(outfd);
1639         
1640         if (cause)
1641                 error("Unable to make runtime: %s", cause);
1642 }
1643
1644 #else /* !__APPLE__ */
1645
1646 static int handle_append_runtime(int handle, char *exename, char **cause_r) {
1647         char *cause= NULL, *runtime= get_runtime_path(exename);
1648         unsigned char buf[1024];
1649         int count, progfd= -1;
1650         
1651         if (!runtime) {
1652                 cause= "Unable to find runtime";
1653                 goto cleanup;
1654         }
1655         
1656         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
1657         if (progfd==-1) {
1658                 cause= "Unable to find runtime";
1659                 goto cleanup;
1660         }
1661
1662         while ((count= read(progfd, buf, sizeof(buf)))>0) {
1663                 if (write(handle, buf, count)!=count) {
1664                         cause= "Unable to write to output file";
1665                         goto cleanup;
1666                 }
1667         }
1668         
1669 cleanup:
1670         if (progfd!=-1)
1671                 close(progfd);
1672         if (runtime)
1673                 MEM_freeN(runtime);
1674         
1675         if (cause) {
1676                 *cause_r= cause;
1677                 return 0;
1678         } else
1679                 return 1;
1680 }
1681
1682 static int handle_write_msb_int(int handle, int i) {
1683         unsigned char buf[4];
1684         buf[0]= (i>>24)&0xFF;
1685         buf[1]= (i>>16)&0xFF;
1686         buf[2]= (i>>8)&0xFF;
1687         buf[3]= (i>>0)&0xFF;
1688         
1689         return (write(handle, buf, 4)==4);
1690 }
1691
1692 void BLO_write_runtime(char *file, char *exename) {
1693         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
1694         char *cause= NULL;
1695         int datastart;
1696         
1697         if (!outfd) {
1698                 cause= "Unable to open output file";
1699                 goto cleanup;
1700         }
1701         if (!handle_append_runtime(outfd, exename, &cause))
1702                 goto cleanup;
1703                 
1704         datastart= lseek(outfd, 0, SEEK_CUR);
1705
1706         write_file_handle(outfd, 0, G.fileflags);
1707         
1708         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
1709                 cause= "Unable to write to output file";
1710                 goto cleanup;
1711         }
1712         
1713 cleanup:
1714         if (outfd!=-1)
1715                 close(outfd);
1716         
1717         if (cause)
1718                 error("Unable to make runtime: %s", cause);
1719 }
1720
1721 #endif /* !__APPLE__ */