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