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