00b29f32127dff5255d1fd996153f7e5216d410c
[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                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
687                         
688                         for(hook= ob->hooks.first; hook; hook= hook->next) {
689                                 writestruct(wd, DATA, "ObHook", 1, hook);
690                                 writedata(wd, DATA, sizeof(int)*hook->totindex, hook->indexar);
691                         }
692                 }
693                 ob= ob->id.next;
694         }
695
696         /* flush helps the compression for undo-save */
697         mywrite(wd, MYWRITE_FLUSH, 0);
698 }
699
700
701 static void write_vfonts(WriteData *wd, ListBase *idbase)
702 {
703         VFont *vf;
704         PackedFile * pf;
705
706         vf= idbase->first;
707         while(vf) {
708                 if(vf->id.us>0 || wd->current) {
709                         /* write LibData */
710                         writestruct(wd, ID_VF, "VFont", 1, vf);
711
712                         /* direct data */
713
714                         if (vf->packedfile) {
715                                 pf = vf->packedfile;
716                                 writestruct(wd, DATA, "PackedFile", 1, pf);
717                                 writedata(wd, DATA, pf->size, pf->data);
718                         }
719                 }
720
721                 vf= vf->id.next;
722         }
723 }
724
725 static void write_ipos(WriteData *wd, ListBase *idbase)
726 {
727         Ipo *ipo;
728         IpoCurve *icu;
729
730         ipo= idbase->first;
731         while(ipo) {
732                 if(ipo->id.us>0 || wd->current) {
733                         /* write LibData */
734                         writestruct(wd, ID_IP, "Ipo", 1, ipo);
735
736                         /* direct data */
737                         icu= ipo->curve.first;
738                         while(icu) {
739                                 writestruct(wd, DATA, "IpoCurve", 1, icu);
740                                 icu= icu->next;
741                         }
742
743                         icu= ipo->curve.first;
744                         while(icu) {
745                                 if(icu->bezt)  writestruct(wd, DATA, "BezTriple", icu->totvert, icu->bezt);
746                                 if(icu->bp)  writestruct(wd, DATA, "BPoint", icu->totvert, icu->bp);
747                                 icu= icu->next;
748                         }
749                 }
750
751                 ipo= ipo->id.next;
752         }
753
754         /* flush helps the compression for undo-save */
755         mywrite(wd, MYWRITE_FLUSH, 0);
756 }
757
758 static void write_keys(WriteData *wd, ListBase *idbase)
759 {
760         Key *key;
761         KeyBlock *kb;
762
763         key= idbase->first;
764         while(key) {
765                 if(key->id.us>0 || wd->current) {
766                         /* write LibData */
767                         writestruct(wd, ID_KE, "Key", 1, key);
768
769                         /* direct data */
770                         kb= key->block.first;
771                         while(kb) {
772                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
773                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
774                                 kb= kb->next;
775                         }
776                 }
777
778                 key= key->id.next;
779         }
780         /* flush helps the compression for undo-save */
781         mywrite(wd, MYWRITE_FLUSH, 0);
782 }
783
784 static void write_cameras(WriteData *wd, ListBase *idbase)
785 {
786         Camera *cam;
787
788         cam= idbase->first;
789         while(cam) {
790                 if(cam->id.us>0 || wd->current) {
791                         /* write LibData */
792                         writestruct(wd, ID_CA, "Camera", 1, cam);
793
794                         /* direct data */
795                         write_scriptlink(wd, &cam->scriptlink);
796                 }
797
798                 cam= cam->id.next;
799         }
800 }
801
802 static void write_mballs(WriteData *wd, ListBase *idbase)
803 {
804         MetaBall *mb;
805         MetaElem *ml;
806
807         mb= idbase->first;
808         while(mb) {
809                 if(mb->id.us>0 || wd->current) {
810                         /* write LibData */
811                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
812
813                         /* direct data */
814                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
815
816                         ml= mb->elems.first;
817                         while(ml) {
818                                 writestruct(wd, DATA, "MetaElem", 1, ml);
819                                 ml= ml->next;
820                         }
821                 }
822                 mb= mb->id.next;
823         }
824 }
825
826 static void write_curves(WriteData *wd, ListBase *idbase)
827 {
828         Curve *cu;
829         Nurb *nu;
830
831         cu= idbase->first;
832         while(cu) {
833                 if(cu->id.us>0 || wd->current) {
834                         /* write LibData */
835                         writestruct(wd, ID_CU, "Curve", 1, cu);
836
837                         /* direct data */
838                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
839
840                         if(cu->vfont) {
841                                 writedata(wd, DATA, cu->len+1, cu->str);
842                         }
843                         else {
844                                 /* is also the order of reading */
845                                 nu= cu->nurb.first;
846                                 while(nu) {
847                                         writestruct(wd, DATA, "Nurb", 1, nu);
848                                         nu= nu->next;
849                                 }
850                                 nu= cu->nurb.first;
851                                 while(nu) {
852                                         if( (nu->type & 7)==CU_BEZIER)
853                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
854                                         else {
855                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
856                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
857                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
858                                         }
859                                         nu= nu->next;
860                                 }
861                         }
862                 }
863                 cu= cu->id.next;
864         }
865
866         /* flush helps the compression for undo-save */
867         mywrite(wd, MYWRITE_FLUSH, 0);
868 }
869
870 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
871 {
872         int     i;
873
874         /* Write the dvert list */
875         writestruct(wd, DATA, "MDeformVert", count, dvlist);
876
877         /* Write deformation data for each dvert */
878         if (dvlist) {
879                 for (i=0; i<count; i++) {
880                         if (dvlist[i].dw)
881                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
882                 }
883         }
884 }
885
886 static void write_meshs(WriteData *wd, ListBase *idbase)
887 {
888         Mesh *mesh;
889
890         mesh= idbase->first;
891         while(mesh) {
892                 if(mesh->id.us>0 || wd->current) {
893                         /* write LibData */
894                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
895
896                         /* direct data */
897                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
898
899                         writestruct(wd, DATA, "MVert", mesh->totvert, mesh->mvert);
900                         writestruct(wd, DATA, "MEdge", mesh->totedge, mesh->medge);
901                         writestruct(wd, DATA, "MFace", mesh->totface, mesh->mface);
902                         writestruct(wd, DATA, "TFace", mesh->totface, mesh->tface);
903                         writestruct(wd, DATA, "MCol", 4*mesh->totface, mesh->mcol);
904                         writestruct(wd, DATA, "MSticky", mesh->totvert, mesh->msticky);
905
906                         write_dverts(wd, mesh->totvert, mesh->dvert);
907
908                 }
909                 mesh= mesh->id.next;
910         }
911 }
912
913 static void write_images(WriteData *wd, ListBase *idbase)
914 {
915         Image *ima;
916         PackedFile * pf;
917
918         ima= idbase->first;
919         while(ima) {
920                 if(ima->id.us>0 || wd->current) {
921                         /* write LibData */
922                         writestruct(wd, ID_IM, "Image", 1, ima);
923
924                         if (ima->packedfile) {
925                                 pf = ima->packedfile;
926                                 writestruct(wd, DATA, "PackedFile", 1, pf);
927                                 writedata(wd, DATA, pf->size, pf->data);
928                         }
929                 }
930                 ima= ima->id.next;
931         }
932         /* flush helps the compression for undo-save */
933         mywrite(wd, MYWRITE_FLUSH, 0);
934 }
935
936 static void write_textures(WriteData *wd, ListBase *idbase)
937 {
938         Tex *tex;
939
940         tex= idbase->first;
941         while(tex) {
942                 if(tex->id.us>0 || wd->current) {
943                         /* write LibData */
944                         writestruct(wd, ID_TE, "Tex", 1, tex);
945
946                         /* direct data */
947                         if(tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
948                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
949                         if(tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
950                 }
951                 tex= tex->id.next;
952         }
953
954         /* flush helps the compression for undo-save */
955         mywrite(wd, MYWRITE_FLUSH, 0);
956 }
957
958 static void write_materials(WriteData *wd, ListBase *idbase)
959 {
960         Material *ma;
961         int a;
962
963         ma= idbase->first;
964         while(ma) {
965                 if(ma->id.us>0 || wd->current) {
966                         /* write LibData */
967                         writestruct(wd, ID_MA, "Material", 1, ma);
968
969                         for(a=0; a<MAX_MTEX; a++) {
970                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
971                         }
972                         
973                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
974                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
975                         
976                         write_scriptlink(wd, &ma->scriptlink);
977                 }
978                 ma= ma->id.next;
979         }
980 }
981
982 static void write_worlds(WriteData *wd, ListBase *idbase)
983 {
984         World *wrld;
985         int a;
986
987         wrld= idbase->first;
988         while(wrld) {
989                 if(wrld->id.us>0 || wd->current) {
990                         /* write LibData */
991                         writestruct(wd, ID_WO, "World", 1, wrld);
992
993                         for(a=0; a<MAX_MTEX; a++) {
994                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
995                         }
996
997                         write_scriptlink(wd, &wrld->scriptlink);
998                 }
999                 wrld= wrld->id.next;
1000         }
1001 }
1002
1003 static void write_lamps(WriteData *wd, ListBase *idbase)
1004 {
1005         Lamp *la;
1006         int a;
1007
1008         la= idbase->first;
1009         while(la) {
1010                 if(la->id.us>0 || wd->current) {
1011                         /* write LibData */
1012                         writestruct(wd, ID_LA, "Lamp", 1, la);
1013
1014                         /* direct data */
1015                         for(a=0; a<MAX_MTEX; a++) {
1016                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1017                         }
1018
1019                         write_scriptlink(wd, &la->scriptlink);
1020                 }
1021                 la= la->id.next;
1022         }
1023 }
1024
1025 static void write_lattices(WriteData *wd, ListBase *idbase)
1026 {
1027         Lattice *lt;
1028
1029         lt= idbase->first;
1030         while(lt) {
1031                 if(lt->id.us>0 || wd->current) {
1032                         /* write LibData */
1033                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1034
1035                         /* direct data */
1036                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1037                 }
1038                 lt= lt->id.next;
1039         }
1040 }
1041
1042 static void write_ikas(WriteData *wd, ListBase *idbase)
1043 {
1044         Ika *ika;
1045         Limb *li;
1046
1047         ika= idbase->first;
1048         while(ika) {
1049                 if(ika->id.us>0 || wd->current) {
1050                         /* write LibData */
1051                         writestruct(wd, ID_IK, "Ika", 1, ika);
1052
1053                         /* direct data */
1054                         li= ika->limbbase.first;
1055                         while(li) {
1056                                 writestruct(wd, DATA, "Limb", 1, li);
1057                                 li= li->next;
1058                         }
1059
1060                         writestruct(wd, DATA, "Deform", ika->totdef, ika->def);
1061                 }
1062                 ika= ika->id.next;
1063         }
1064 }
1065
1066 static void write_scenes(WriteData *wd, ListBase *scebase)
1067 {
1068         Scene *sce;
1069         Base *base;
1070         Editing *ed;
1071         Sequence *seq;
1072         MetaStack *ms;
1073         Strip *strip;
1074
1075         sce= scebase->first;
1076         while(sce) {
1077                 /* write LibData */
1078                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1079
1080                 /* direct data */
1081                 base= sce->base.first;
1082                 while(base) {
1083                         writestruct(wd, DATA, "Base", 1, base);
1084                         base= base->next;
1085                 }
1086
1087                 writestruct(wd, DATA, "Radio", 1, sce->radio);
1088
1089                 ed= sce->ed;
1090                 if(ed) {
1091                         writestruct(wd, DATA, "Editing", 1, ed);
1092
1093                         /* reset write flags too */
1094                         WHILE_SEQ(&ed->seqbase) {
1095                                 if(seq->strip) seq->strip->done= 0;
1096                                 writestruct(wd, DATA, "Sequence", 1, seq);
1097                         }
1098                         END_SEQ
1099
1100                         WHILE_SEQ(&ed->seqbase) {
1101                                 if(seq->strip && seq->strip->done==0) {
1102                                         /* write strip with 'done' at 0 because readfile */
1103
1104                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1105                                         if(seq->effectdata) {
1106                                                 switch(seq->type){
1107                                                         case SEQ_WIPE:
1108                                                                 writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1109                                                                 break;
1110                                                         case SEQ_GLOW:
1111                                                                 writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1112                                                                 break;
1113                                                 }
1114                                         }
1115
1116                                         strip= seq->strip;
1117                                         writestruct(wd, DATA, "Strip", 1, strip);
1118
1119                                         if(seq->type==SEQ_IMAGE)
1120                                                 writestruct(wd, DATA, "StripElem", strip->len, strip->stripdata);
1121                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_SOUND)
1122                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1123
1124                                         strip->done= 1;
1125                                 }
1126                         }
1127                         END_SEQ
1128                                 
1129                         /* new; meta stack too, even when its nasty restore code */
1130                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1131                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1132                         }
1133                 }
1134
1135                 write_scriptlink(wd, &sce->scriptlink);
1136
1137                 if (sce->r.avicodecdata) {
1138                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1139                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1140                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1141                 }
1142
1143                 if (sce->r.qtcodecdata) {
1144                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1145                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1146                 }
1147
1148                 sce= sce->id.next;
1149         }
1150         /* flush helps the compression for undo-save */
1151         mywrite(wd, MYWRITE_FLUSH, 0);
1152 }
1153
1154 static void write_screens(WriteData *wd, ListBase *scrbase)
1155 {
1156         bScreen *sc;
1157         ScrArea *sa;
1158         ScrVert *sv;
1159         ScrEdge *se;
1160
1161         sc= scrbase->first;
1162         while(sc) {
1163                 /* write LibData */
1164                 writestruct(wd, ID_SCR, "Screen", 1, sc);
1165
1166                 /* direct data */
1167                 sv= sc->vertbase.first;
1168                 while(sv) {
1169                         writestruct(wd, DATA, "ScrVert", 1, sv);
1170                         sv= sv->next;
1171                 }
1172
1173                 se= sc->edgebase.first;
1174                 while(se) {
1175                         writestruct(wd, DATA, "ScrEdge", 1, se);
1176                         se= se->next;
1177                 }
1178
1179                 sa= sc->areabase.first;
1180                 while(sa) {
1181                         SpaceLink *sl;
1182                         Panel *pa;
1183
1184                         writestruct(wd, DATA, "ScrArea", 1, sa);
1185
1186                         pa= sa->panels.first;
1187                         while(pa) {
1188                                 writestruct(wd, DATA, "Panel", 1, pa);
1189                                 pa= pa->next;
1190                         }
1191
1192                         sl= sa->spacedata.first;
1193                         while(sl) {
1194                                 if(sl->spacetype==SPACE_VIEW3D) {
1195                                         View3D *v3d= (View3D*) sl;
1196                                         writestruct(wd, DATA, "View3D", 1, v3d);
1197                                         if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
1198                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
1199                                 }
1200                                 else if(sl->spacetype==SPACE_IPO) {
1201                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
1202                                 }
1203                                 else if(sl->spacetype==SPACE_BUTS) {
1204                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
1205                                 }
1206                                 else if(sl->spacetype==SPACE_FILE) {
1207                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
1208                                 }
1209                                 else if(sl->spacetype==SPACE_SEQ) {
1210                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
1211                                 }
1212                                 else if(sl->spacetype==SPACE_OOPS) {
1213                                         SpaceOops *so= (SpaceOops *)sl;
1214                                         Oops *oops;
1215
1216                                         /* cleanup */
1217                                         oops= so->oops.first;
1218                                         while(oops) {
1219                                                 Oops *oopsn= oops->next;
1220                                                 if(oops->id==0) {
1221                                                         BLI_remlink(&so->oops, oops);
1222                                                         free_oops(oops);
1223                                                 }
1224                                                 oops= oopsn;
1225                                         }
1226
1227                                         /* ater cleanup, because of listbase! */
1228                                         writestruct(wd, DATA, "SpaceOops", 1, so);
1229
1230                                         oops= so->oops.first;
1231                                         while(oops) {
1232                                                 writestruct(wd, DATA, "Oops", 1, oops);
1233                                                 oops= oops->next;
1234                                         }
1235                                         /* outliner */
1236                                         if(so->treestore) {
1237                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
1238                                                 if(so->treestore->data)
1239                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
1240                                         }
1241                                 }
1242                                 else if(sl->spacetype==SPACE_IMAGE) {
1243                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
1244                                 }
1245                                 else if(sl->spacetype==SPACE_IMASEL) {
1246                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
1247                                 }
1248                                 else if(sl->spacetype==SPACE_TEXT) {
1249                                         writestruct(wd, DATA, "SpaceText", 1, sl);
1250                                 }
1251                                 else if(sl->spacetype==SPACE_SCRIPT) {
1252                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
1253                                 }
1254                                 else if(sl->spacetype==SPACE_ACTION) {
1255                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
1256                                 }
1257                                 else if(sl->spacetype==SPACE_SOUND) {
1258                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
1259                                 }
1260                                 else if(sl->spacetype==SPACE_NLA){
1261                                         writestruct(wd, DATA, "SpaceNla", 1, sl);
1262                                 }
1263                                 sl= sl->next;
1264                         }
1265
1266                         sa= sa->next;
1267                 }
1268
1269                 sc= sc->id.next;
1270         }
1271 }
1272
1273 static void write_libraries(WriteData *wd, Main *main)
1274 {
1275         ListBase *lbarray[30];
1276         ID *id;
1277         int a, tot, foundone;
1278
1279         while(main) {
1280
1281                 a=tot= set_listbasepointers(main, lbarray);
1282
1283                 /* test: is lib being used */
1284                 foundone= 0;
1285                 while(tot--) {
1286                         id= lbarray[tot]->first;
1287                         while(id) {
1288                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
1289                                         foundone= 1;
1290                                         break;
1291                                 }
1292                                 id= id->next;
1293                         }
1294                         if(foundone) break;
1295                 }
1296
1297                 if(foundone) {
1298                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
1299
1300                         while(a--) {
1301                                 id= lbarray[a]->first;
1302                                 while(id) {
1303                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
1304
1305                                                 writestruct(wd, ID_ID, "ID", 1, id);
1306                                         }
1307                                         id= id->next;
1308                                 }
1309                         }
1310                 }
1311
1312                 main= main->next;
1313         }
1314 }
1315
1316 static void write_bone(WriteData *wd, Bone* bone)
1317 {
1318         Bone*   cbone;
1319
1320 //      write_constraints(wd, &bone->constraints);
1321
1322         // Write this bone
1323         writestruct(wd, DATA, "Bone", 1, bone);
1324
1325         // Write Children
1326         cbone= bone->childbase.first;
1327         while(cbone) {
1328                 write_bone(wd, cbone);
1329                 cbone= cbone->next;
1330         }
1331 }
1332
1333 static void write_armatures(WriteData *wd, ListBase *idbase)
1334 {
1335         bArmature       *arm;
1336         Bone            *bone;
1337
1338         arm=idbase->first;
1339         while (arm) {
1340                 if (arm->id.us>0 || wd->current) {
1341                         writestruct(wd, ID_AR, "bArmature", 1, arm);
1342
1343                         /* Direct data */
1344                         bone= arm->bonebase.first;
1345                         while(bone) {
1346                                 write_bone(wd, bone);
1347                                 bone=bone->next;
1348                         }
1349                 }
1350                 arm=arm->id.next;
1351         }
1352
1353         /* flush helps the compression for undo-save */
1354         mywrite(wd, MYWRITE_FLUSH, 0);
1355 }
1356
1357 static void write_actions(WriteData *wd, ListBase *idbase)
1358 {
1359         bAction                 *act;
1360         bActionChannel  *chan;
1361         act=idbase->first;
1362         while (act) {
1363                 if (act->id.us>0 || wd->current) {
1364                         writestruct(wd, ID_AC, "bAction", 1, act);
1365
1366                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1367                                 writestruct(wd, DATA, "bActionChannel", 1, chan);
1368                                 write_constraint_channels(wd, &chan->constraintChannels);
1369                         }
1370                 }
1371                 act=act->id.next;
1372         }
1373 }
1374
1375 static void write_texts(WriteData *wd, ListBase *idbase)
1376 {
1377         Text *text;
1378         TextLine *tmp;
1379
1380         text= idbase->first;
1381         while(text) {
1382                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
1383
1384                 /* write LibData */
1385                 writestruct(wd, ID_TXT, "Text", 1, text);
1386                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
1387
1388                 if(!(text->flags & TXT_ISEXT)) {
1389                         /* now write the text data, in two steps for optimization in the readfunction */
1390                         tmp= text->lines.first;
1391                         while (tmp) {
1392                                 writestruct(wd, DATA, "TextLine", 1, tmp);
1393                                 tmp= tmp->next;
1394                         }
1395
1396                         tmp= text->lines.first;
1397                         while (tmp) {
1398                                 writedata(wd, DATA, tmp->len+1, tmp->line);
1399                                 tmp= tmp->next;
1400                         }
1401                 }
1402                 text= text->id.next;
1403         }
1404
1405         /* flush helps the compression for undo-save */
1406         mywrite(wd, MYWRITE_FLUSH, 0);
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 || wd->current) {
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         /* flush helps the compression for undo-save */
1455         mywrite(wd, MYWRITE_FLUSH, 0);
1456 }
1457
1458 static void write_groups(WriteData *wd, ListBase *idbase)
1459 {
1460         Group *group;
1461         GroupKey *gk;
1462         GroupObject *go;
1463         ObjectKey *ok;
1464
1465         group= idbase->first;
1466         while(group) {
1467                 if(group->id.us>0 || wd->current) {
1468                         /* write LibData */
1469                         writestruct(wd, ID_GR, "Group", 1, group);
1470
1471                         gk= group->gkey.first;
1472                         while(gk) {
1473                                 writestruct(wd, DATA, "GroupKey", 1, gk);
1474                                 gk= gk->next;
1475                         }
1476
1477                         go= group->gobject.first;
1478                         while(go) {
1479                                 writestruct(wd, DATA, "GroupObject", 1, go);
1480                                 go= go->next;
1481                         }
1482                         go= group->gobject.first;
1483                         while(go) {
1484                                 ok= go->okey.first;
1485                                 while(ok) {
1486                                         writestruct(wd, DATA, "ObjectKey", 1, ok);
1487                                         ok= ok->next;
1488                                 }
1489                                 go= go->next;
1490                         }
1491
1492                 }
1493                 group= group->id.next;
1494         }
1495 }
1496
1497 static void write_global(WriteData *wd)
1498 {
1499         FileGlobal fg;
1500
1501         fg.curscreen= G.curscreen;
1502         fg.curscene= G.scene;
1503         fg.displaymode= G.displaymode;
1504         fg.winpos= G.winpos;
1505         fg.fileflags= (G.fileflags & ~G_FILE_NO_UI);    // prevent to save this, is not good convention, and feature with concerns...
1506         fg.globalf= G.f;
1507
1508         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
1509 }
1510
1511 /* if *mem there's filesave to memory */
1512 static int write_file_handle(int handle, MemFile *compare, MemFile *current, int write_user_block, int write_flags)
1513 {
1514         BHead bhead;
1515         ListBase mainlist;
1516         char buf[13];
1517         WriteData *wd;
1518 /*      int data; */ /*unused*/
1519
1520         mainlist.first= mainlist.last= G.main;
1521         G.main->next= NULL;
1522
1523         blo_split_main(&mainlist);
1524
1525         wd= bgnwrite(handle, compare, current, write_flags);
1526         
1527         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (G.order==B_ENDIAN)?'V':'v', G.version);
1528         mywrite(wd, buf, 12);
1529
1530         write_renderinfo(wd);
1531         
1532         if(current==NULL)
1533                 write_screens  (wd, &G.main->screen);   // no UI save
1534         write_scenes   (wd, &G.main->scene);
1535         write_curves   (wd, &G.main->curve);
1536         write_mballs   (wd, &G.main->mball);
1537         write_images   (wd, &G.main->image);
1538         write_cameras  (wd, &G.main->camera);
1539         write_lamps    (wd, &G.main->lamp);
1540         write_lattices (wd, &G.main->latt);
1541         write_ikas     (wd, &G.main->ika);
1542         write_vfonts   (wd, &G.main->vfont);
1543         write_ipos     (wd, &G.main->ipo);
1544         write_keys     (wd, &G.main->key);
1545         write_worlds   (wd, &G.main->world);
1546         write_texts    (wd, &G.main->text);
1547         write_sounds   (wd, &G.main->sound);
1548         write_groups   (wd, &G.main->group);
1549         write_armatures(wd, &G.main->armature);
1550         write_actions  (wd, &G.main->action);
1551         write_objects  (wd, &G.main->object);
1552         write_materials(wd, &G.main->mat);
1553         write_textures (wd, &G.main->tex);
1554         write_meshs    (wd, &G.main->mesh);
1555         write_libraries(wd,  G.main->next);
1556
1557         write_global(wd);
1558         if (write_user_block) {
1559                 write_userdef(wd);
1560         }
1561
1562         /* dna as last, because (to be implemented) test for which structs are written */
1563         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
1564
1565         /* end of file */
1566         memset(&bhead, 0, sizeof(BHead));
1567         bhead.code= ENDB;
1568         mywrite(wd, &bhead, sizeof(BHead));
1569
1570         blo_join_main(&mainlist);
1571         G.main= mainlist.first;
1572
1573         return endwrite(wd);
1574 }
1575
1576 /* return: success (1) */
1577 int BLO_write_file(char *dir, int write_flags, char **error_r)
1578 {
1579         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
1580         char tempname[FILE_MAXDIR+FILE_MAXFILE];
1581         int file, fout, write_user_block;
1582
1583         sprintf(tempname, "%s@", dir);
1584
1585         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
1586         if(file == -1) {
1587                 *error_r= "Unable to open";
1588                 return 0;
1589         }
1590
1591         BLI_make_file_string(G.sce, userfilename, BLI_gethome(), ".B.blend");
1592
1593         write_user_block= BLI_streq(dir, userfilename);
1594
1595         fout= write_file_handle(file, NULL,NULL, write_user_block, write_flags);
1596         close(file);
1597
1598         if(!fout) {
1599                 if(BLI_rename(tempname, dir) < 0) {
1600                         *error_r= "Can't change old file. File saved with @";
1601                         return 0;
1602                 }
1603         } else {
1604                 remove(tempname);
1605
1606                 *error_r= "Not enough diskspace";
1607                 return 0;
1608         }
1609
1610         return 1;
1611 }
1612
1613 /* return: success (1) */
1614 int BLO_write_file_mem(MemFile *compare, MemFile *current, int write_flags, char **error_r)
1615 {
1616         int err;
1617
1618         err= write_file_handle(0, compare, current, 0, write_flags);
1619         
1620         if(err==0) return 1;
1621         return 0;
1622 }
1623
1624
1625         /* Runtime writing */
1626
1627 #ifdef WIN32
1628 #define PATHSEPERATOR           "\\"
1629 #else
1630 #define PATHSEPERATOR           "/"
1631 #endif
1632
1633 static char *get_install_dir(void) {
1634         extern char bprogname[];
1635         char *tmpname = BLI_strdup(bprogname);
1636         char *cut;
1637
1638 #ifdef __APPLE__
1639         cut = strstr(tmpname, ".app");
1640         if (cut) cut[0] = 0;
1641 #endif
1642
1643         cut = BLI_last_slash(tmpname);
1644
1645         if (cut) {
1646                 cut[0] = 0;
1647                 return tmpname;
1648         } else {
1649                 MEM_freeN(tmpname);
1650                 return NULL;
1651         }
1652 }
1653
1654 static char *get_runtime_path(char *exename) {
1655         char *installpath= get_install_dir();
1656
1657         if (!installpath) {
1658                 return NULL;
1659         } else {
1660                 char *path= MEM_mallocN(strlen(installpath)+strlen(PATHSEPERATOR)+strlen(exename)+1, "runtimepath");
1661                 strcpy(path, installpath);
1662                 strcat(path, PATHSEPERATOR);
1663                 strcat(path, exename);
1664
1665                 MEM_freeN(installpath);
1666
1667                 return path;
1668         }
1669 }
1670
1671 #ifdef __APPLE__
1672
1673 static int recursive_copy_runtime(char *outname, char *exename, char **cause_r) 
1674 {
1675         char *cause = NULL, *runtime = get_runtime_path(exename);
1676         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
1677         int progfd = -1;
1678
1679         if (!runtime) {
1680                 cause= "Unable to find runtime";
1681                 goto cleanup;
1682         }
1683         //printf("runtimepath %s\n", runtime);
1684                 
1685         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
1686         if (progfd==-1) {
1687                 cause= "Unable to find runtime";
1688                 goto cleanup;
1689         }
1690
1691         sprintf(command, "/bin/cp -R \"%s\" \"%s\"", runtime, outname);
1692         //printf("command %s\n", command);
1693         if (system(command) == -1) {
1694                 cause = "Couldn't copy runtime";
1695         }
1696
1697 cleanup:
1698         if (progfd!=-1)
1699                 close(progfd);
1700         if (runtime)
1701                 MEM_freeN(runtime);
1702
1703         if (cause) {
1704                 *cause_r= cause;
1705                 return 0;
1706         } else
1707                 return 1;
1708 }
1709
1710 void BLO_write_runtime(char *file, char *exename) {
1711         char gamename[FILE_MAXDIR+FILE_MAXFILE];
1712         int outfd = -1;
1713         char *cause= NULL;
1714
1715         // remove existing file / bundle
1716         //printf("Delete file %s\n", file);
1717         BLI_delete(file, NULL, TRUE);
1718
1719         if (!recursive_copy_runtime(file, exename, &cause))
1720                 goto cleanup;
1721
1722         strcpy(gamename, file);
1723         strcat(gamename, "/Contents/Resources/game.blend");
1724         //printf("gamename %s\n", gamename);
1725         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
1726         if (outfd != -1) {
1727
1728                 write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
1729
1730                 if (write(outfd, " ", 1) != 1) {
1731                         cause= "Unable to write to output file";
1732                         goto cleanup;
1733                 }
1734         } else {
1735                 cause = "Unable to open blenderfile";
1736         }
1737
1738 cleanup:
1739         if (outfd!=-1)
1740                 close(outfd);
1741
1742         if (cause)
1743                 error("Unable to make runtime: %s", cause);
1744 }
1745
1746 #else /* !__APPLE__ */
1747
1748 static int handle_append_runtime(int handle, char *exename, char **cause_r) {
1749         char *cause= NULL, *runtime= get_runtime_path(exename);
1750         unsigned char buf[1024];
1751         int count, progfd= -1;
1752
1753         if (!runtime) {
1754                 cause= "Unable to find runtime";
1755                 goto cleanup;
1756         }
1757
1758         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
1759         if (progfd==-1) {
1760                 cause= "Unable to find runtime";
1761                 goto cleanup;
1762         }
1763
1764         while ((count= read(progfd, buf, sizeof(buf)))>0) {
1765                 if (write(handle, buf, count)!=count) {
1766                         cause= "Unable to write to output file";
1767                         goto cleanup;
1768                 }
1769         }
1770
1771 cleanup:
1772         if (progfd!=-1)
1773                 close(progfd);
1774         if (runtime)
1775                 MEM_freeN(runtime);
1776
1777         if (cause) {
1778                 *cause_r= cause;
1779                 return 0;
1780         } else
1781                 return 1;
1782 }
1783
1784 static int handle_write_msb_int(int handle, int i) {
1785         unsigned char buf[4];
1786         buf[0]= (i>>24)&0xFF;
1787         buf[1]= (i>>16)&0xFF;
1788         buf[2]= (i>>8)&0xFF;
1789         buf[3]= (i>>0)&0xFF;
1790
1791         return (write(handle, buf, 4)==4);
1792 }
1793
1794 void BLO_write_runtime(char *file, char *exename) {
1795         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
1796         char *cause= NULL;
1797         int datastart;
1798
1799         if (!outfd) {
1800                 cause= "Unable to open output file";
1801                 goto cleanup;
1802         }
1803         if (!handle_append_runtime(outfd, exename, &cause))
1804                 goto cleanup;
1805
1806         datastart= lseek(outfd, 0, SEEK_CUR);
1807
1808         write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
1809
1810         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
1811                 cause= "Unable to write to output file";
1812                 goto cleanup;
1813         }
1814
1815 cleanup:
1816         if (outfd!=-1)
1817                 close(outfd);
1818
1819         if (cause)
1820                 error("Unable to make runtime: %s", cause);
1821 }
1822
1823 #endif /* !__APPLE__ */