== CMake ==
[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 #include "zlib.h"
87
88 #ifndef WIN32
89 #include <unistd.h>
90 #else
91 #include "winsock2.h"
92 #include "BLI_winstuff.h"
93 #include <io.h>
94 #include <process.h> // for getpid
95 #endif
96
97 #include <math.h>
98 #include <fcntl.h>
99 #include <stdio.h>
100 #include <string.h>
101 #include <stdlib.h>
102
103 #include "nla.h" //  __NLA is defined
104
105 #include "DNA_armature_types.h"
106 #include "DNA_action_types.h"
107 #include "DNA_actuator_types.h"
108 #include "DNA_brush_types.h"
109 #include "DNA_camera_types.h"
110 #include "DNA_color_types.h"
111 #include "DNA_constraint_types.h"
112 #include "DNA_controller_types.h"
113 #include "DNA_curve_types.h"
114 #include "DNA_customdata_types.h"
115 #include "DNA_effect_types.h"
116 #include "DNA_group_types.h"
117 #include "DNA_image_types.h"
118 #include "DNA_ipo_types.h"
119 #include "DNA_fileglobal_types.h"
120 #include "DNA_key_types.h"
121 #include "DNA_lattice_types.h"
122 #include "DNA_listBase.h" /* for Listbase, the type of samples, ...*/
123 #include "DNA_lamp_types.h"
124 #include "DNA_meta_types.h"
125 #include "DNA_mesh_types.h"
126 #include "DNA_meshdata_types.h"
127 #include "DNA_material_types.h"
128 #include "DNA_modifier_types.h"
129 #include "DNA_nla_types.h"
130 #include "DNA_node_types.h"
131 #include "DNA_object_types.h"
132 #include "DNA_object_force.h"
133 #include "DNA_oops_types.h"
134 #include "DNA_packedFile_types.h"
135 #include "DNA_property_types.h"
136 #include "DNA_scene_types.h"
137 #include "DNA_sdna_types.h"
138 #include "DNA_sequence_types.h"
139 #include "DNA_sensor_types.h"
140 #include "DNA_space_types.h"
141 #include "DNA_screen_types.h"
142 #include "DNA_sound_types.h"
143 #include "DNA_texture_types.h"
144 #include "DNA_text_types.h"
145 #include "DNA_view3d_types.h"
146 #include "DNA_vfont_types.h"
147 #include "DNA_userdef_types.h"
148 #include "DNA_world_types.h"
149
150 #include "MEM_guardedalloc.h" // MEM_freeN
151 #include "BLI_blenlib.h"
152 #include "BLI_linklist.h"
153
154 #include "BKE_action.h"
155 #include "BKE_bad_level_calls.h" // build_seqar (from WHILE_SEQ) free_oops error
156 #include "BKE_blender.h"
157 #include "BKE_curve.h"
158 #include "BKE_customdata.h"
159 #include "BKE_constraint.h"
160 #include "BKE_global.h" // for G
161 #include "BKE_library.h" // for  set_listbasepointers
162 #include "BKE_main.h" // G.main
163 #include "BKE_node.h"
164 #include "BKE_packedFile.h" // for packAll
165 #include "BKE_screen.h" // for waitcursor
166 #include "BKE_scene.h" // for do_seq
167 #include "BKE_sound.h" /* ... and for samples */
168 #include "BKE_utildefines.h" // for defines
169 #include "BKE_modifier.h"
170 #include "BKE_idprop.h"
171 #ifdef WITH_VERSE
172 #include "BKE_verse.h"
173 #include "BIF_verse.h"
174 #endif
175
176 #include "GEN_messaging.h"
177
178 #include "BLO_writefile.h"
179 #include "BLO_readfile.h"
180 #include "BLO_undofile.h"
181
182 #include "readfile.h"
183 #include "genfile.h"
184
185 #include <errno.h>
186
187 /* ********* my write, buffered writing with minimum 50k chunks ************ */
188
189 typedef struct {
190         struct SDNA *sdna;
191
192         int file;
193         unsigned char *buf;
194         MemFile *compare, *current;
195         
196         int tot, count, error, memsize;
197 } WriteData;
198
199 static WriteData *writedata_new(int file)
200 {
201         extern unsigned char DNAstr[];  /* DNA.c */
202         extern int DNAlen;
203
204         WriteData *wd= MEM_callocN(sizeof(*wd), "writedata");
205
206                 /* XXX, see note about this in readfile.c, remove
207                  * once we have an xp lock - zr
208                  */
209
210         if (wd == NULL) return NULL;
211
212         wd->sdna= dna_sdna_from_data(DNAstr, DNAlen, 0);
213
214         wd->file= file;
215
216         wd->buf= MEM_mallocN(100000, "wd->buf");
217
218         return wd;
219 }
220
221 static void writedata_do_write(WriteData *wd, void *mem, int memlen)
222 {
223         if ((wd == NULL) || wd->error || (mem == NULL) || memlen < 1) return;
224         if (wd->error) return;
225
226         /* memory based save */
227         if(wd->current) {
228                 add_memfilechunk(NULL, wd->current, mem, memlen);
229         }
230         else {
231                 if (write(wd->file, mem, memlen) != memlen)
232                         wd->error= 1;
233                 
234         }
235 }
236
237 static void writedata_free(WriteData *wd)
238 {
239         dna_freestructDNA(wd->sdna);
240
241         MEM_freeN(wd->buf);
242         MEM_freeN(wd);
243 }
244
245 /***/
246
247 int mywfile;
248
249 /**
250  * Low level WRITE(2) wrapper that buffers data
251  * @param adr Pointer to new chunk of data
252  * @param len Length of new chunk of data
253  * @warning Talks to other functions with global parameters
254  */
255  
256 #define MYWRITE_FLUSH   NULL
257
258 static void mywrite( WriteData *wd, void *adr, int len)
259 {
260         if (wd->error) return;
261
262         if(adr==MYWRITE_FLUSH) {
263                 if(wd->count) {
264                         writedata_do_write(wd, wd->buf, wd->count);
265                         wd->count= 0;
266                 }
267                 return;
268         }
269
270         wd->tot+= len;
271         
272         if(len>50000) {
273                 if(wd->count) {
274                         writedata_do_write(wd, wd->buf, wd->count);
275                         wd->count= 0;
276                 }
277                 writedata_do_write(wd, adr, len);
278                 return;
279         }
280         if(len+wd->count>99999) {
281                 writedata_do_write(wd, wd->buf, wd->count);
282                 wd->count= 0;
283         }
284         memcpy(&wd->buf[wd->count], adr, len);
285         wd->count+= len;
286
287 }
288
289 /**
290  * BeGiN initializer for mywrite
291  * @param file File descriptor
292  * @param write_flags Write parameters
293  * @warning Talks to other functions with global parameters
294  */
295 static WriteData *bgnwrite(int file, MemFile *compare, MemFile *current, int write_flags)
296 {
297         WriteData *wd= writedata_new(file);
298
299         if (wd == NULL) return NULL;
300
301         wd->compare= compare;
302         wd->current= current;
303         /* this inits comparing */
304         add_memfilechunk(compare, NULL, NULL, 0);
305         
306         return wd;
307 }
308
309 /**
310  * END the mywrite wrapper
311  * @return 1 if write failed
312  * @return unknown global variable otherwise
313  * @warning Talks to other functions with global parameters
314  */
315 static int endwrite(WriteData *wd)
316 {
317         int err;
318
319         if (wd->count) {
320                 writedata_do_write(wd, wd->buf, wd->count);
321                 wd->count= 0;
322         }
323         
324         err= wd->error;
325         writedata_free(wd);
326
327         return err;
328 }
329
330 /* ********** WRITE FILE ****************** */
331
332 static void writestruct(WriteData *wd, int filecode, char *structname, int nr, void *adr)
333 {
334         BHead bh;
335         short *sp;
336
337         if(adr==NULL || nr==0) return;
338
339         /* init BHead */
340         bh.code= filecode;
341         bh.old= adr;
342         bh.nr= nr;
343
344         bh.SDNAnr= dna_findstruct_nr(wd->sdna, structname);
345         if(bh.SDNAnr== -1) {
346                 printf("error: can't find SDNA code <%s>\n", structname);
347                 return;
348         }
349         sp= wd->sdna->structs[bh.SDNAnr];
350
351         bh.len= nr*wd->sdna->typelens[sp[0]];
352
353         if(bh.len==0) return;
354
355         mywrite(wd, &bh, sizeof(BHead));
356         mywrite(wd, adr, bh.len);
357 }
358
359 static void writedata(WriteData *wd, int filecode, int len, void *adr)  /* do not use for structs */
360 {
361         BHead bh;
362
363         if(adr==0) return;
364         if(len==0) return;
365
366         len+= 3;
367         len-= ( len % 4);
368
369         /* init BHead */
370         bh.code= filecode;
371         bh.old= adr;
372         bh.nr= 1;
373         bh.SDNAnr= 0;
374         bh.len= len;
375
376         mywrite(wd, &bh, sizeof(BHead));
377         if(len) mywrite(wd, adr, len);
378 }
379
380 /* *************** writing some direct data structs used in more code parts **************** */
381 /*These functions are used by blender's .blend system for file saving/loading.*/
382 void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd);
383 void IDP_WriteProperty(IDProperty *prop, void *wd);
384
385 void IDP_WriteArray(IDProperty *prop, void *wd)
386 {
387         /*REMEMBER to set totalen to len in the linking code!!*/
388         if (prop->data.pointer) {
389                 writedata(wd, DATA, MEM_allocN_len(prop->data.pointer), prop->data.pointer);
390         }
391 }
392
393 void IDP_WriteString(IDProperty *prop, void *wd)
394 {
395         /*REMEMBER to set totalen to len in the linking code!!*/
396         writedata(wd, DATA, prop->len+1, prop->data.pointer);
397 }
398
399 void IDP_WriteGroup(IDProperty *prop, void *wd)
400 {
401         IDProperty *loop;
402
403         for (loop=prop->data.group.first; loop; loop=loop->next) {
404                 IDP_WriteProperty(loop, wd);
405         }
406 }
407
408 /* Functions to read/write ID Properties */
409 void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd)
410 {
411         switch (prop->type) {
412                 case IDP_GROUP:
413                         IDP_WriteGroup(prop, wd);
414                         break;
415                 case IDP_STRING:
416                         IDP_WriteString(prop, wd);
417                         break;
418                 case IDP_ARRAY:
419                         IDP_WriteArray(prop, wd);
420                         break;
421         }
422 }
423
424 void IDP_WriteProperty(IDProperty *prop, void *wd)
425 {
426         writestruct(wd, DATA, "IDProperty", 1, prop);
427         IDP_WriteProperty_OnlyData(prop, wd);
428 }
429
430 static void write_curvemapping(WriteData *wd, CurveMapping *cumap)
431 {
432         int a;
433         
434         writestruct(wd, DATA, "CurveMapping", 1, cumap);
435         for(a=0; a<CM_TOT; a++)
436                 writestruct(wd, DATA, "CurveMapPoint", cumap->cm[a].totpoint, cumap->cm[a].curve);
437 }
438
439 /* this is only direct data, tree itself should have been written */
440 static void write_nodetree(WriteData *wd, bNodeTree *ntree)
441 {
442         bNode *node;
443         bNodeSocket *sock;
444         bNodeLink *link;
445         
446         /* for link_list() speed, we write per list */
447         
448         for(node= ntree->nodes.first; node; node= node->next)
449                 writestruct(wd, DATA, "bNode", 1, node);
450
451         for(node= ntree->nodes.first; node; node= node->next) {
452                 if(node->storage) {
453                         /* could be handlerized at some point, now only 1 exception still */
454                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
455                                 write_curvemapping(wd, node->storage);
456                         else if(ntree->type==NTREE_COMPOSIT && (node->type==CMP_NODE_TIME || node->type==CMP_NODE_CURVE_VEC || node->type==CMP_NODE_CURVE_RGB))
457                                 write_curvemapping(wd, node->storage);
458                         else 
459                                 writestruct(wd, DATA, node->typeinfo->storagename, 1, node->storage);
460                 }
461                 for(sock= node->inputs.first; sock; sock= sock->next)
462                         writestruct(wd, DATA, "bNodeSocket", 1, sock);
463                 for(sock= node->outputs.first; sock; sock= sock->next)
464                         writestruct(wd, DATA, "bNodeSocket", 1, sock);
465         }
466         
467         for(link= ntree->links.first; link; link= link->next)
468                 writestruct(wd, DATA, "bNodeLink", 1, link);
469 }
470
471 static void write_scriptlink(WriteData *wd, ScriptLink *slink)
472 {
473         writedata(wd, DATA, sizeof(void *)*slink->totscript, slink->scripts);
474         writedata(wd, DATA, sizeof(short)*slink->totscript, slink->flag);
475 }
476
477 static void write_renderinfo(WriteData *wd)             /* for renderdeamon */
478 {
479         Scene *sce;
480         int data[8];
481
482         sce= G.main->scene.first;
483         while(sce) {
484                 if(sce->id.lib==0  && ( sce==G.scene || (sce->r.scemode & R_BG_RENDER)) ) {
485                         data[0]= sce->r.sfra;
486                         data[1]= sce->r.efra;
487
488                         memset(data+2, 0, sizeof(int)*6);
489                         strncpy((char *)(data+2), sce->id.name+2, 21);
490
491                         writedata(wd, REND, 32, data);
492                 }
493                 sce= sce->id.next;
494         }
495 }
496
497 static void write_userdef(WriteData *wd)
498 {
499         bTheme *btheme;
500
501         writestruct(wd, USER, "UserDef", 1, &U);
502
503         btheme= U.themes.first;
504         while(btheme) {
505                 writestruct(wd, DATA, "bTheme", 1, btheme);
506                 btheme= btheme->next;
507         }
508 }
509
510 static void write_effects(WriteData *wd, ListBase *lb)
511 {
512         Effect *eff;
513
514         eff= lb->first;
515         while(eff) {
516
517                 switch(eff->type) {
518                 case EFF_PARTICLE:
519                         writestruct(wd, DATA, "PartEff", 1, eff);
520                         break;
521                 default:
522                         writedata(wd, DATA, MEM_allocN_len(eff), eff);
523                 }
524
525                 eff= eff->next;
526         }
527 }
528
529 static void write_properties(WriteData *wd, ListBase *lb)
530 {
531         bProperty *prop;
532
533         prop= lb->first;
534         while(prop) {
535                 writestruct(wd, DATA, "bProperty", 1, prop);
536
537                 if(prop->poin && prop->poin != &prop->data)
538                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
539
540                 prop= prop->next;
541         }
542 }
543
544 static void write_sensors(WriteData *wd, ListBase *lb)
545 {
546         bSensor *sens;
547
548         sens= lb->first;
549         while(sens) {
550                 writestruct(wd, DATA, "bSensor", 1, sens);
551
552                 writedata(wd, DATA, sizeof(void *)*sens->totlinks, sens->links);
553
554                 switch(sens->type) {
555                 case SENS_NEAR:
556                         writestruct(wd, DATA, "bNearSensor", 1, sens->data);
557                         break;
558                 case SENS_MOUSE:
559                         writestruct(wd, DATA, "bMouseSensor", 1, sens->data);
560                         break;
561                 case SENS_TOUCH:
562                         writestruct(wd, DATA, "bTouchSensor", 1, sens->data);
563                         break;
564                 case SENS_KEYBOARD:
565                         writestruct(wd, DATA, "bKeyboardSensor", 1, sens->data);
566                         break;
567                 case SENS_PROPERTY:
568                         writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
569                         break;
570                 case SENS_COLLISION:
571                         writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
572                         break;
573                 case SENS_RADAR:
574                         writestruct(wd, DATA, "bRadarSensor", 1, sens->data);
575                         break;
576                 case SENS_RANDOM:
577                         writestruct(wd, DATA, "bRandomSensor", 1, sens->data);
578                         break;
579                 case SENS_RAY:
580                         writestruct(wd, DATA, "bRaySensor", 1, sens->data);
581                         break;
582                 case SENS_MESSAGE:
583                         writestruct(wd, DATA, "bMessageSensor", 1, sens->data);
584                         break;
585                 case SENS_JOYSTICK:
586                         writestruct(wd, DATA, "bJoystickSensor", 1, sens->data);
587                         break;
588                 default:
589                         ; /* error: don't know how to write this file */
590                 }
591
592                 sens= sens->next;
593         }
594 }
595
596 static void write_controllers(WriteData *wd, ListBase *lb)
597 {
598         bController *cont;
599
600         cont= lb->first;
601         while(cont) {
602                 writestruct(wd, DATA, "bController", 1, cont);
603
604                 writedata(wd, DATA, sizeof(void *)*cont->totlinks, cont->links);
605
606                 switch(cont->type) {
607                 case CONT_EXPRESSION:
608                         writestruct(wd, DATA, "bExpressionCont", 1, cont->data);
609                         break;
610                 case CONT_PYTHON:
611                         writestruct(wd, DATA, "bPythonCont", 1, cont->data);
612                         break;
613                 default:
614                         ; /* error: don't know how to write this file */
615                 }
616
617                 cont= cont->next;
618         }
619 }
620
621 static void write_actuators(WriteData *wd, ListBase *lb)
622 {
623         bActuator *act;
624
625         act= lb->first;
626         while(act) {
627                 writestruct(wd, DATA, "bActuator", 1, act);
628
629                 switch(act->type) {
630                 case ACT_ACTION:
631                         writestruct(wd, DATA, "bActionActuator", 1, act->data);
632                         break;
633                 case ACT_SOUND:
634                         writestruct(wd, DATA, "bSoundActuator", 1, act->data);
635                         break;
636                 case ACT_CD:
637                         writestruct(wd, DATA, "bCDActuator", 1, act->data);
638                         break;
639                 case ACT_OBJECT:
640                         writestruct(wd, DATA, "bObjectActuator", 1, act->data);
641                         break;
642                 case ACT_IPO:
643                         writestruct(wd, DATA, "bIpoActuator", 1, act->data);
644                         break;
645                 case ACT_PROPERTY:
646                         writestruct(wd, DATA, "bPropertyActuator", 1, act->data);
647                         break;
648                 case ACT_CAMERA:
649                         writestruct(wd, DATA, "bCameraActuator", 1, act->data);
650                         break;
651                 case ACT_CONSTRAINT:
652                         writestruct(wd, DATA, "bConstraintActuator", 1, act->data);
653                         break;
654                 case ACT_EDIT_OBJECT:
655                         writestruct(wd, DATA, "bEditObjectActuator", 1, act->data);
656                         break;
657                 case ACT_SCENE:
658                         writestruct(wd, DATA, "bSceneActuator", 1, act->data);
659                         break;
660                 case ACT_GROUP:
661                         writestruct(wd, DATA, "bGroupActuator", 1, act->data);
662                         break;
663                 case ACT_RANDOM:
664                         writestruct(wd, DATA, "bRandomActuator", 1, act->data);
665                         break;
666                 case ACT_MESSAGE:
667                         writestruct(wd, DATA, "bMessageActuator", 1, act->data);
668                         break;
669                 case ACT_GAME:
670                         writestruct(wd, DATA, "bGameActuator", 1, act->data);
671                         break;
672                 case ACT_VISIBILITY:
673                         writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
674                         break;
675                 default:
676                         ; /* error: don't know how to write this file */
677                 }
678
679                 act= act->next;
680         }
681 }
682
683 static void write_nlastrips(WriteData *wd, ListBase *nlabase)
684 {
685         bActionStrip *strip;
686         bActionModifier *amod;
687         
688         for (strip=nlabase->first; strip; strip=strip->next)
689                 writestruct(wd, DATA, "bActionStrip", 1, strip);
690         for (strip=nlabase->first; strip; strip=strip->next) {
691                 for(amod= strip->modifiers.first; amod; amod= amod->next)
692                         writestruct(wd, DATA, "bActionModifier", 1, amod);
693         }
694 }
695
696 static void write_constraints(WriteData *wd, ListBase *conlist)
697 {
698         bConstraint *con;
699
700         for (con=conlist->first; con; con=con->next) {
701                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
702                 
703                 /* Write the specific data */
704                 if (cti && con->data) {
705                         /* firstly, just write the plain con->data struct */
706                         writestruct(wd, DATA, cti->structName, 1, con->data);
707                         
708                         /* do any constraint specific stuff */
709                         switch (con->type) {
710                                 case CONSTRAINT_TYPE_PYTHON:
711                                 {
712                                         bPythonConstraint *data = (bPythonConstraint*) con->data;
713                                         
714                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
715                                          of library blocks that implement this.*/
716                                         IDP_WriteProperty(data->prop, wd);
717                                 }
718                                 break;
719                         }
720                 }
721                 
722                 /* Write the constraint */
723                 writestruct(wd, DATA, "bConstraint", 1, con);
724         }
725 }
726
727 static void write_pose(WriteData *wd, bPose *pose)
728 {
729         bPoseChannel *chan;
730
731         /* Write each channel */
732         if (!pose)
733                 return;
734
735         /* Write channels */
736         for (chan=pose->chanbase.first; chan; chan=chan->next) {
737                 write_constraints(wd, &chan->constraints);
738                 
739                 /* prevent crashes with autosave, when a bone duplicated in editmode has not yet been assigned to its posechannel */
740                 if (chan->bone) 
741                         chan->selectflag= chan->bone->flag & (BONE_SELECTED|BONE_ACTIVE); /* gets restored on read, for library armatures */
742                 
743                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
744         }
745
746         /* Write this pose */
747         writestruct(wd, DATA, "bPose", 1, pose);
748 }
749
750 static void write_defgroups(WriteData *wd, ListBase *defbase)
751 {
752         bDeformGroup    *defgroup;
753
754         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
755                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
756 }
757
758 static void write_constraint_channels(WriteData *wd, ListBase *chanbase)
759 {
760         bConstraintChannel *chan;
761
762         for (chan = chanbase->first; chan; chan=chan->next)
763                 writestruct(wd, DATA, "bConstraintChannel", 1, chan);
764
765 }
766
767 static void write_modifiers(WriteData *wd, ListBase *modbase)
768 {
769         ModifierData *md;
770
771         if (modbase == NULL) return;
772         for (md=modbase->first; md; md= md->next) {
773                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
774                 if (mti == NULL) return;
775                 
776                 writestruct(wd, DATA, mti->structName, 1, md);
777                         
778                 if (md->type==eModifierType_Hook) {
779                         HookModifierData *hmd = (HookModifierData*) md;
780                         
781                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
782                 }
783         }
784 }
785
786 static void write_objects(WriteData *wd, ListBase *idbase)
787 {
788         Object *ob;
789         int a;
790         
791         ob= idbase->first;
792         while(ob) {
793                 if(ob->id.us>0 || wd->current) {
794                         /* write LibData */
795 #ifdef WITH_VERSE
796                         /* pointer at vnode stored in file have to be NULL */
797                         struct VNode *vnode = (VNode*)ob->vnode;
798                         if(vnode) ob->vnode = NULL;
799 #endif
800                         writestruct(wd, ID_OB, "Object", 1, ob);
801 #ifdef WITH_VERSE
802                         if(vnode) ob->vnode = (void*)vnode;
803 #endif
804
805                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
806                           of library blocks that implement this.*/
807                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
808
809                         /* direct data */
810                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
811                         write_effects(wd, &ob->effect);
812                         write_properties(wd, &ob->prop);
813                         write_sensors(wd, &ob->sensors);
814                         write_controllers(wd, &ob->controllers);
815                         write_actuators(wd, &ob->actuators);
816                         write_scriptlink(wd, &ob->scriptlink);
817                         write_pose(wd, ob->pose);
818                         write_defgroups(wd, &ob->defbase);
819                         write_constraints(wd, &ob->constraints);
820                         write_constraint_channels(wd, &ob->constraintChannels);
821                         write_nlastrips(wd, &ob->nlastrips);
822                         
823                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
824                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
825                         if(ob->soft) {
826                                 SoftBody *sb= ob->soft;
827                                 if(sb->keys) {
828                                         writedata(wd, DATA, sizeof(void *)*sb->totkey, sb->keys);
829                                         for(a=0; a<sb->totkey; a++) {
830                                                 writestruct(wd, DATA, "SBVertex", sb->totpoint, sb->keys[a]);
831                                         }
832                                 }
833                         }
834                         writestruct(wd, DATA, "FluidsimSettings", 1, ob->fluidsimSettings); // NT
835                         
836                         write_modifiers(wd, &ob->modifiers);
837                 }
838                 ob= ob->id.next;
839         }
840
841         /* flush helps the compression for undo-save */
842         mywrite(wd, MYWRITE_FLUSH, 0);
843 }
844
845
846 static void write_vfonts(WriteData *wd, ListBase *idbase)
847 {
848         VFont *vf;
849         PackedFile * pf;
850
851         vf= idbase->first;
852         while(vf) {
853                 if(vf->id.us>0 || wd->current) {
854                         /* write LibData */
855                         writestruct(wd, ID_VF, "VFont", 1, vf);
856                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
857
858                         /* direct data */
859
860                         if (vf->packedfile) {
861                                 pf = vf->packedfile;
862                                 writestruct(wd, DATA, "PackedFile", 1, pf);
863                                 writedata(wd, DATA, pf->size, pf->data);
864                         }
865                 }
866
867                 vf= vf->id.next;
868         }
869 }
870
871 static void write_ipos(WriteData *wd, ListBase *idbase)
872 {
873         Ipo *ipo;
874         IpoCurve *icu;
875
876         ipo= idbase->first;
877         while(ipo) {
878                 if(ipo->id.us>0 || wd->current) {
879                         /* write LibData */
880                         writestruct(wd, ID_IP, "Ipo", 1, ipo);
881                         if (ipo->id.properties) IDP_WriteProperty(ipo->id.properties, wd);
882
883                         /* direct data */
884                         icu= ipo->curve.first;
885                         while(icu) {
886                                 writestruct(wd, DATA, "IpoCurve", 1, icu);
887                                 icu= icu->next;
888                         }
889
890                         icu= ipo->curve.first;
891                         while(icu) {
892                                 if(icu->bezt)  writestruct(wd, DATA, "BezTriple", icu->totvert, icu->bezt);
893                                 if(icu->bp)  writestruct(wd, DATA, "BPoint", icu->totvert, icu->bp);
894                                 if(icu->driver)  writestruct(wd, DATA, "IpoDriver", 1, icu->driver);
895                                 icu= icu->next;
896                         }
897                 }
898
899                 ipo= ipo->id.next;
900         }
901
902         /* flush helps the compression for undo-save */
903         mywrite(wd, MYWRITE_FLUSH, 0);
904 }
905
906 static void write_keys(WriteData *wd, ListBase *idbase)
907 {
908         Key *key;
909         KeyBlock *kb;
910
911         key= idbase->first;
912         while(key) {
913                 if(key->id.us>0 || wd->current) {
914                         /* write LibData */
915                         writestruct(wd, ID_KE, "Key", 1, key);
916                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
917
918                         /* direct data */
919                         kb= key->block.first;
920                         while(kb) {
921                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
922                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
923                                 kb= kb->next;
924                         }
925                 }
926
927                 key= key->id.next;
928         }
929         /* flush helps the compression for undo-save */
930         mywrite(wd, MYWRITE_FLUSH, 0);
931 }
932
933 static void write_cameras(WriteData *wd, ListBase *idbase)
934 {
935         Camera *cam;
936
937         cam= idbase->first;
938         while(cam) {
939                 if(cam->id.us>0 || wd->current) {
940                         /* write LibData */
941                         writestruct(wd, ID_CA, "Camera", 1, cam);
942                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
943
944                         /* direct data */
945                         write_scriptlink(wd, &cam->scriptlink);
946                 }
947
948                 cam= cam->id.next;
949         }
950 }
951
952 static void write_mballs(WriteData *wd, ListBase *idbase)
953 {
954         MetaBall *mb;
955         MetaElem *ml;
956
957         mb= idbase->first;
958         while(mb) {
959                 if(mb->id.us>0 || wd->current) {
960                         /* write LibData */
961                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
962                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
963
964                         /* direct data */
965                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
966
967                         ml= mb->elems.first;
968                         while(ml) {
969                                 writestruct(wd, DATA, "MetaElem", 1, ml);
970                                 ml= ml->next;
971                         }
972                 }
973                 mb= mb->id.next;
974         }
975 }
976
977 int amount_of_chars(char *str)
978 {
979         // Since the data is saved as UTF-8 to the cu->str
980         // The cu->len is not same as the strlen(cu->str)
981         return strlen(str);
982 }
983
984 static void write_curves(WriteData *wd, ListBase *idbase)
985 {
986         Curve *cu;
987         Nurb *nu;
988
989         cu= idbase->first;
990         while(cu) {
991                 if(cu->id.us>0 || wd->current) {
992                         /* write LibData */
993                         writestruct(wd, ID_CU, "Curve", 1, cu);
994
995                         /* direct data */
996                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
997                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
998
999                         if(cu->vfont) {
1000                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1001                                 writestruct(wd, DATA, "CharInfo", cu->len, cu->strinfo);
1002                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);                           
1003                         }
1004                         else {
1005                                 /* is also the order of reading */
1006                                 nu= cu->nurb.first;
1007                                 while(nu) {
1008                                         writestruct(wd, DATA, "Nurb", 1, nu);
1009                                         nu= nu->next;
1010                                 }
1011                                 nu= cu->nurb.first;
1012                                 while(nu) {
1013                                         if( (nu->type & 7)==CU_BEZIER)
1014                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1015                                         else {
1016                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1017                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1018                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1019                                         }
1020                                         nu= nu->next;
1021                                 }
1022                         }
1023                 }
1024                 cu= cu->id.next;
1025         }
1026
1027         /* flush helps the compression for undo-save */
1028         mywrite(wd, MYWRITE_FLUSH, 0);
1029 }
1030
1031 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1032 {
1033         if (dvlist) {
1034                 int     i;
1035                 
1036                 /* Write the dvert list */
1037                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1038                 
1039                 /* Write deformation data for each dvert */
1040                 for (i=0; i<count; i++) {
1041                         if (dvlist[i].dw)
1042                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1043                 }
1044         }
1045 }
1046
1047 static void write_customdata(WriteData *wd, int count, CustomData *data, int partial_type, int partial_count)
1048 {
1049         int i;
1050
1051         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1052
1053         for (i=0; i<data->totlayer; i++) {
1054                 CustomDataLayer *layer= &data->layers[i];
1055                 char *structname;
1056                 int structnum, datasize;
1057
1058                 if (layer->type == CD_MDEFORMVERT) {
1059                         /* layer types that allocate own memory need special handling */
1060                         write_dverts(wd, count, layer->data);
1061                 }
1062                 else {
1063                         CustomData_file_write_info(layer->type, &structname, &structnum);
1064                         if (structnum) {
1065                                 /* when using partial visibility, the MEdge and MFace layers
1066                                    are smaller than the original, so their type and count is
1067                                    passed to make this work */
1068                                 if (layer->type != partial_type) datasize= structnum*count;
1069                                 else datasize= structnum*partial_count;
1070
1071                                 writestruct(wd, DATA, structname, datasize, layer->data);
1072                         }
1073                         else
1074                                 printf("error: this CustomDataLayer must not be written to file\n");
1075                 }
1076         }
1077 }
1078
1079 static void write_meshs(WriteData *wd, ListBase *idbase)
1080 {
1081         Mesh *mesh;
1082         MultiresLevel *lvl;
1083
1084         mesh= idbase->first;
1085         while(mesh) {
1086                 if(mesh->id.us>0 || wd->current) {
1087                         /* write LibData */
1088 #ifdef WITH_VERSE
1089                         struct VNode *vnode = (VNode*)mesh->vnode;
1090                         if(vnode) {
1091                                 /* mesh has to be created from verse geometry node*/
1092                                 create_meshdata_from_geom_node(mesh, vnode);
1093                                 /* pointer at verse node can't be stored in file */
1094                                 mesh->vnode = NULL;
1095                         }
1096 #endif
1097
1098                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
1099 #ifdef WITH_VERSE
1100                         if(vnode) mesh->vnode = (void*)vnode;
1101 #endif
1102
1103                         /* direct data */
1104                         if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1105
1106                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1107
1108                         if(mesh->pv) {
1109                                 write_customdata(wd, mesh->pv->totvert, &mesh->vdata, -1, 0);
1110                                 write_customdata(wd, mesh->pv->totedge, &mesh->edata,
1111                                         CD_MEDGE, mesh->totedge);
1112                                 write_customdata(wd, mesh->pv->totface, &mesh->fdata,
1113                                         CD_MFACE, mesh->totface);
1114                         }
1115                         else {
1116                                 write_customdata(wd, mesh->totvert, &mesh->vdata, -1, 0);
1117                                 write_customdata(wd, mesh->totedge, &mesh->edata, -1, 0);
1118                                 write_customdata(wd, mesh->totface, &mesh->fdata, -1, 0);
1119                         }
1120
1121                         /* Multires data */
1122                         writestruct(wd, DATA, "Multires", 1, mesh->mr);
1123                         if(mesh->mr) {
1124                                 lvl= mesh->mr->levels.first;
1125                                 if(lvl) {
1126                                         write_customdata(wd, lvl->totvert, &mesh->mr->vdata, -1, 0);
1127                                         write_customdata(wd, lvl->totface, &mesh->mr->fdata, -1, 0);
1128                                         writedata(wd, DATA, sizeof(short)*lvl->totedge, mesh->mr->edge_flags);
1129                                         writedata(wd, DATA, sizeof(char)*lvl->totedge, mesh->mr->edge_creases);
1130                                 }
1131
1132                                 for(; lvl; lvl= lvl->next) {
1133                                         writestruct(wd, DATA, "MultiresLevel", 1, lvl);
1134                                         writestruct(wd, DATA, "MultiresFace", lvl->totface, lvl->faces);
1135                                         writestruct(wd, DATA, "MultiresEdge", lvl->totedge, lvl->edges);
1136                                         writestruct(wd, DATA, "MultiresColFace", lvl->totface, lvl->colfaces);
1137                                 }
1138
1139                                 lvl= mesh->mr->levels.last;
1140                                 if(lvl)
1141                                         writestruct(wd, DATA, "MVert", lvl->totvert, mesh->mr->verts);
1142                         }
1143
1144                         /* PMV data */
1145                         if(mesh->pv) {
1146                                 writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
1147                                 writedata(wd, DATA, sizeof(unsigned int)*mesh->pv->totvert, mesh->pv->vert_map);
1148                                 writedata(wd, DATA, sizeof(int)*mesh->pv->totedge, mesh->pv->edge_map);
1149                                 writestruct(wd, DATA, "MFace", mesh->pv->totface, mesh->pv->old_faces);
1150                                 writestruct(wd, DATA, "MEdge", mesh->pv->totedge, mesh->pv->old_edges);
1151                         }
1152                 }
1153                 mesh= mesh->id.next;
1154         }
1155 }
1156
1157 static void write_lattices(WriteData *wd, ListBase *idbase)
1158 {
1159         Lattice *lt;
1160         
1161         lt= idbase->first;
1162         while(lt) {
1163                 if(lt->id.us>0 || wd->current) {
1164                         /* write LibData */
1165                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1166                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1167
1168                         /* direct data */
1169                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1170                         
1171                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1172                         
1173                 }
1174                 lt= lt->id.next;
1175         }
1176 }
1177
1178 static void write_previews(WriteData *wd, PreviewImage *prv)
1179 {
1180         if (prv) {
1181                 short w = prv->w[1];
1182                 short h = prv->h[1];
1183                 unsigned int *rect = prv->rect[1];
1184                 /* don't write out large previews if not requested */
1185                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1186                         prv->w[1] = 0;
1187                         prv->h[1] = 0;
1188                         prv->rect[1] = NULL;
1189                 }
1190                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1191                 if (prv->rect[0]) writedata(wd, DATA, prv->w[0]*prv->h[0]*sizeof(unsigned int), prv->rect[0]);
1192                 if (prv->rect[1]) writedata(wd, DATA, prv->w[1]*prv->h[1]*sizeof(unsigned int), prv->rect[1]);
1193
1194                 /* restore preview, we still want to keep it in memory even if not saved to file */
1195                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1196                         prv->w[1] = w;
1197                         prv->h[1] = h;
1198                         prv->rect[1] = rect;
1199                 }
1200         }
1201 }
1202
1203 static void write_images(WriteData *wd, ListBase *idbase)
1204 {
1205         Image *ima;
1206         PackedFile * pf;
1207
1208
1209         ima= idbase->first;
1210         while(ima) {
1211                 if(ima->id.us>0 || wd->current) {
1212                         /* write LibData */
1213                         writestruct(wd, ID_IM, "Image", 1, ima);
1214                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1215
1216                         if (ima->packedfile) {
1217                                 pf = ima->packedfile;
1218                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1219                                 writedata(wd, DATA, pf->size, pf->data);
1220                         }
1221
1222                         write_previews(wd, ima->preview);
1223
1224                         }
1225                 ima= ima->id.next;
1226         }
1227         /* flush helps the compression for undo-save */
1228         mywrite(wd, MYWRITE_FLUSH, 0);
1229 }
1230
1231 static void write_textures(WriteData *wd, ListBase *idbase)
1232 {
1233         Tex *tex;
1234
1235         tex= idbase->first;
1236         while(tex) {
1237                 if(tex->id.us>0 || wd->current) {
1238                         /* write LibData */
1239                         writestruct(wd, ID_TE, "Tex", 1, tex);
1240                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1241
1242                         /* direct data */
1243                         if(tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1244                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1245                         if(tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1246                         
1247                         write_previews(wd, tex->preview);
1248                 }
1249                 tex= tex->id.next;
1250         }
1251
1252         /* flush helps the compression for undo-save */
1253         mywrite(wd, MYWRITE_FLUSH, 0);
1254 }
1255
1256 static void write_materials(WriteData *wd, ListBase *idbase)
1257 {
1258         Material *ma;
1259         int a;
1260
1261         ma= idbase->first;
1262         while(ma) {
1263                 if(ma->id.us>0 || wd->current) {
1264                         /* write LibData */
1265                         writestruct(wd, ID_MA, "Material", 1, ma);
1266                         
1267                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1268                           of library blocks that implement this.*/
1269                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1270                           set yet :) */
1271                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1272
1273                         for(a=0; a<MAX_MTEX; a++) {
1274                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1275                         }
1276                         
1277                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1278                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1279                         
1280                         write_scriptlink(wd, &ma->scriptlink);
1281                         
1282                         /* nodetree is integral part of material, no libdata */
1283                         if(ma->nodetree) {
1284                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1285                                 write_nodetree(wd, ma->nodetree);
1286                         }
1287
1288                         write_previews(wd, ma->preview);                        
1289                 }
1290                 ma= ma->id.next;
1291         }
1292 }
1293
1294 static void write_worlds(WriteData *wd, ListBase *idbase)
1295 {
1296         World *wrld;
1297         int a;
1298
1299         wrld= idbase->first;
1300         while(wrld) {
1301                 if(wrld->id.us>0 || wd->current) {
1302                         /* write LibData */
1303                         writestruct(wd, ID_WO, "World", 1, wrld);
1304                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1305
1306                         for(a=0; a<MAX_MTEX; a++) {
1307                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1308                         }
1309
1310                         write_scriptlink(wd, &wrld->scriptlink);
1311
1312                         write_previews(wd, wrld->preview);
1313
1314                 }
1315                 wrld= wrld->id.next;
1316         }
1317 }
1318
1319 static void write_lamps(WriteData *wd, ListBase *idbase)
1320 {
1321         Lamp *la;
1322         int a;
1323
1324         la= idbase->first;
1325         while(la) {
1326                 if(la->id.us>0 || wd->current) {
1327                         /* write LibData */
1328                         writestruct(wd, ID_LA, "Lamp", 1, la);
1329                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1330
1331                         /* direct data */
1332                         for(a=0; a<MAX_MTEX; a++) {
1333                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1334                         }
1335
1336                         if(la->curfalloff)
1337                                 write_curvemapping(wd, la->curfalloff); 
1338                         
1339                         write_scriptlink(wd, &la->scriptlink);
1340
1341                         write_previews(wd, la->preview);
1342
1343                 }
1344                 la= la->id.next;
1345         }
1346 }
1347
1348
1349 static void write_scenes(WriteData *wd, ListBase *scebase)
1350 {
1351         Scene *sce;
1352         Base *base;
1353         Editing *ed;
1354         Sequence *seq;
1355         MetaStack *ms;
1356         Strip *strip;
1357         TimeMarker *marker;
1358         SceneRenderLayer *srl;
1359         int a;
1360         
1361         sce= scebase->first;
1362         while(sce) {
1363                 /* write LibData */
1364                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1365                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1366
1367                 /* direct data */
1368                 base= sce->base.first;
1369                 while(base) {
1370                         writestruct(wd, DATA, "Base", 1, base);
1371                         base= base->next;
1372                 }
1373
1374                 writestruct(wd, DATA, "Radio", 1, sce->radio);
1375                 writestruct(wd, DATA, "ToolSettings", 1, sce->toolsettings);
1376
1377                 for(a=0; a<MAX_MTEX; ++a)
1378                         writestruct(wd, DATA, "MTex", 1, sce->sculptdata.mtex[a]);
1379
1380                 ed= sce->ed;
1381                 if(ed) {
1382                         writestruct(wd, DATA, "Editing", 1, ed);
1383
1384                         /* reset write flags too */
1385                         WHILE_SEQ(&ed->seqbase) {
1386                                 if(seq->strip) seq->strip->done= 0;
1387                                 writestruct(wd, DATA, "Sequence", 1, seq);
1388                         }
1389                         END_SEQ
1390
1391                         WHILE_SEQ(&ed->seqbase) {
1392                                 if(seq->strip && seq->strip->done==0) {
1393                                         /* write strip with 'done' at 0 because readfile */
1394
1395                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1396                                         if(seq->effectdata) {
1397                                                 switch(seq->type){
1398                                                 case SEQ_COLOR:
1399                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
1400                                                         break;
1401                                                 case SEQ_SPEED:
1402                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
1403                                                         break;
1404                                                 case SEQ_WIPE:
1405                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1406                                                         break;
1407                                                 case SEQ_GLOW:
1408                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1409                                                         break;
1410                                                 case SEQ_TRANSFORM:
1411                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
1412                                                         break;
1413                                                 }
1414                                         }
1415
1416                                         strip= seq->strip;
1417                                         writestruct(wd, DATA, "Strip", 1, strip);
1418
1419                                         if(seq->type==SEQ_IMAGE)
1420                                                 writestruct(wd, DATA, "StripElem", strip->len, strip->stripdata);
1421                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
1422                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1423
1424                                         strip->done= 1;
1425                                 }
1426                         }
1427                         END_SEQ
1428                                 
1429                         /* new; meta stack too, even when its nasty restore code */
1430                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1431                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1432                         }
1433                 }
1434
1435                 write_scriptlink(wd, &sce->scriptlink);
1436
1437                 if (sce->r.avicodecdata) {
1438                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1439                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1440                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1441                 }
1442
1443                 if (sce->r.qtcodecdata) {
1444                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1445                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1446                 }
1447
1448                 /* writing dynamic list of TimeMarkers to the blend file */
1449                 for(marker= sce->markers.first; marker; marker= marker->next)
1450                         writestruct(wd, DATA, "TimeMarker", 1, marker);
1451                 
1452                 for(srl= sce->r.layers.first; srl; srl= srl->next)
1453                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
1454                 
1455                 if(sce->nodetree) {
1456                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
1457                         write_nodetree(wd, sce->nodetree);
1458                 }
1459                 
1460                 sce= sce->id.next;
1461         }
1462         /* flush helps the compression for undo-save */
1463         mywrite(wd, MYWRITE_FLUSH, 0);
1464 }
1465
1466 static void write_screens(WriteData *wd, ListBase *scrbase)
1467 {
1468         bScreen *sc;
1469         ScrArea *sa;
1470         ScrVert *sv;
1471         ScrEdge *se;
1472
1473         sc= scrbase->first;
1474         while(sc) {
1475                 /* write LibData */
1476                 writestruct(wd, ID_SCR, "Screen", 1, sc);
1477                 if (sc->id.properties) IDP_WriteProperty(sc->id.properties, wd);
1478
1479                 /* direct data */
1480                 sv= sc->vertbase.first;
1481                 while(sv) {
1482                         writestruct(wd, DATA, "ScrVert", 1, sv);
1483                         sv= sv->next;
1484                 }
1485
1486                 se= sc->edgebase.first;
1487                 while(se) {
1488                         writestruct(wd, DATA, "ScrEdge", 1, se);
1489                         se= se->next;
1490                 }
1491
1492                 sa= sc->areabase.first;
1493                 while(sa) {
1494                         SpaceLink *sl;
1495                         Panel *pa;
1496
1497                         writestruct(wd, DATA, "ScrArea", 1, sa);
1498
1499                         pa= sa->panels.first;
1500                         while(pa) {
1501                                 writestruct(wd, DATA, "Panel", 1, pa);
1502                                 pa= pa->next;
1503                         }
1504
1505                         /* space handler scriptlinks */
1506                         write_scriptlink(wd, &sa->scriptlink);
1507
1508                         sl= sa->spacedata.first;
1509                         while(sl) {
1510                                 if(sl->spacetype==SPACE_VIEW3D) {
1511                                         View3D *v3d= (View3D*) sl;
1512                                         writestruct(wd, DATA, "View3D", 1, v3d);
1513                                         if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
1514                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
1515                                         if(v3d->clipbb) writestruct(wd, DATA, "BoundBox", 1, v3d->clipbb);
1516                                 }
1517                                 else if(sl->spacetype==SPACE_IPO) {
1518                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
1519                                 }
1520                                 else if(sl->spacetype==SPACE_BUTS) {
1521                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
1522                                 }
1523                                 else if(sl->spacetype==SPACE_FILE) {
1524                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
1525                                 }
1526                                 else if(sl->spacetype==SPACE_SEQ) {
1527                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
1528                                 }
1529                                 else if(sl->spacetype==SPACE_OOPS) {
1530                                         SpaceOops *so= (SpaceOops *)sl;
1531                                         Oops *oops;
1532
1533                                         /* cleanup */
1534                                         oops= so->oops.first;
1535                                         while(oops) {
1536                                                 Oops *oopsn= oops->next;
1537                                                 if(oops->id==0) {
1538                                                         BLI_remlink(&so->oops, oops);
1539                                                         free_oops(oops);
1540                                                 }
1541                                                 oops= oopsn;
1542                                         }
1543
1544                                         /* ater cleanup, because of listbase! */
1545                                         writestruct(wd, DATA, "SpaceOops", 1, so);
1546
1547                                         oops= so->oops.first;
1548                                         while(oops) {
1549                                                 writestruct(wd, DATA, "Oops", 1, oops);
1550                                                 oops= oops->next;
1551                                         }
1552                                         /* outliner */
1553                                         if(so->treestore) {
1554                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
1555                                                 if(so->treestore->data)
1556                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
1557                                         }
1558                                 }
1559                                 else if(sl->spacetype==SPACE_IMAGE) {
1560                                         SpaceImage *sima= (SpaceImage *)sl;
1561                                         
1562                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
1563                                         if(sima->cumap)
1564                                                 write_curvemapping(wd, sima->cumap);                                    
1565                                 }
1566                                 else if(sl->spacetype==SPACE_IMASEL) {
1567                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
1568                                 }
1569                                 else if(sl->spacetype==SPACE_TEXT) {
1570                                         writestruct(wd, DATA, "SpaceText", 1, sl);
1571                                 }
1572                                 else if(sl->spacetype==SPACE_SCRIPT) {
1573                                         SpaceScript *sc = (SpaceScript*)sl;
1574                                         sc->but_refs = NULL;
1575                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
1576                                 }
1577                                 else if(sl->spacetype==SPACE_ACTION) {
1578                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
1579                                 }
1580                                 else if(sl->spacetype==SPACE_SOUND) {
1581                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
1582                                 }
1583                                 else if(sl->spacetype==SPACE_NLA){
1584                                         writestruct(wd, DATA, "SpaceNla", 1, sl);
1585                                 }
1586                                 else if(sl->spacetype==SPACE_TIME){
1587                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
1588                                 }
1589                                 else if(sl->spacetype==SPACE_NODE){
1590                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
1591                                 }
1592                                 sl= sl->next;
1593                         }
1594
1595                         sa= sa->next;
1596                 }
1597
1598                 sc= sc->id.next;
1599         }
1600 }
1601
1602 static void write_libraries(WriteData *wd, Main *main)
1603 {
1604         ListBase *lbarray[30];
1605         ID *id;
1606         int a, tot, foundone;
1607
1608         for(; main; main= main->next) {
1609
1610                 a=tot= set_listbasepointers(main, lbarray);
1611
1612                 /* test: is lib being used */
1613                 foundone= 0;
1614                 while(tot--) {
1615                         for(id= lbarray[tot]->first; id; id= id->next) {
1616                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
1617                                         foundone= 1;
1618                                         break;
1619                                 }
1620                         }
1621                         if(foundone) break;
1622                 }
1623
1624                 if(foundone) {
1625                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
1626
1627                         while(a--) {
1628                                 for(id= lbarray[a]->first; id; id= id->next) {
1629                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
1630                                                 writestruct(wd, ID_ID, "ID", 1, id);
1631                                         }
1632                                 }
1633                         }
1634                 }
1635         }
1636 }
1637
1638 static void write_bone(WriteData *wd, Bone* bone)
1639 {
1640         Bone*   cbone;
1641
1642         // PATCH for upward compatibility after 2.37+ armature recode
1643         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
1644                 
1645         // Write this bone
1646         writestruct(wd, DATA, "Bone", 1, bone);
1647         
1648         // Write Children
1649         cbone= bone->childbase.first;
1650         while(cbone) {
1651                 write_bone(wd, cbone);
1652                 cbone= cbone->next;
1653         }
1654 }
1655
1656 static void write_armatures(WriteData *wd, ListBase *idbase)
1657 {
1658         bArmature       *arm;
1659         Bone            *bone;
1660
1661         arm=idbase->first;
1662         while (arm) {
1663                 if (arm->id.us>0 || wd->current) {
1664                         writestruct(wd, ID_AR, "bArmature", 1, arm);
1665                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
1666
1667                         /* Direct data */
1668                         bone= arm->bonebase.first;
1669                         while(bone) {
1670                                 write_bone(wd, bone);
1671                                 bone=bone->next;
1672                         }
1673                 }
1674                 arm=arm->id.next;
1675         }
1676
1677         /* flush helps the compression for undo-save */
1678         mywrite(wd, MYWRITE_FLUSH, 0);
1679 }
1680
1681 static void write_actions(WriteData *wd, ListBase *idbase)
1682 {
1683         bAction                 *act;
1684         bActionChannel  *chan;
1685         
1686         for(act=idbase->first; act; act= act->id.next) {
1687                 if (act->id.us>0 || wd->current) {
1688                         writestruct(wd, ID_AC, "bAction", 1, act);
1689                         if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
1690
1691                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1692                                 writestruct(wd, DATA, "bActionChannel", 1, chan);
1693                                 write_constraint_channels(wd, &chan->constraintChannels);
1694                         }
1695                 }
1696         }
1697 }
1698
1699 static void write_texts(WriteData *wd, ListBase *idbase)
1700 {
1701         Text *text;
1702         TextLine *tmp;
1703
1704         text= idbase->first;
1705         while(text) {
1706                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
1707
1708                 /* write LibData */
1709                 writestruct(wd, ID_TXT, "Text", 1, text);
1710                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
1711                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
1712
1713                 if(!(text->flags & TXT_ISEXT)) {
1714                         /* now write the text data, in two steps for optimization in the readfunction */
1715                         tmp= text->lines.first;
1716                         while (tmp) {
1717                                 writestruct(wd, DATA, "TextLine", 1, tmp);
1718                                 tmp= tmp->next;
1719                         }
1720
1721                         tmp= text->lines.first;
1722                         while (tmp) {
1723                                 writedata(wd, DATA, tmp->len+1, tmp->line);
1724                                 tmp= tmp->next;
1725                         }
1726                 }
1727                 text= text->id.next;
1728         }
1729
1730         /* flush helps the compression for undo-save */
1731         mywrite(wd, MYWRITE_FLUSH, 0);
1732 }
1733
1734 static void write_sounds(WriteData *wd, ListBase *idbase)
1735 {
1736         bSound *sound;
1737         bSample *sample;
1738
1739         PackedFile * pf;
1740
1741         // set all samples to unsaved status
1742
1743         sample = samples->first;
1744         while (sample) {
1745                 sample->flags |= SAMPLE_NEEDS_SAVE;
1746                 sample = sample->id.next;
1747         }
1748
1749         sound= idbase->first;
1750         while(sound) {
1751                 if(sound->id.us>0 || wd->current) {
1752                         // do we need to save the packedfile as well ?
1753                         sample = sound->sample;
1754                         if (sample) {
1755                                 if (sample->flags & SAMPLE_NEEDS_SAVE) {
1756                                         sound->newpackedfile = sample->packedfile;
1757                                         sample->flags &= ~SAMPLE_NEEDS_SAVE;
1758                                 } else {
1759                                         sound->newpackedfile = NULL;
1760                                 }
1761                         }
1762
1763                         /* write LibData */
1764                         writestruct(wd, ID_SO, "bSound", 1, sound);
1765                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
1766
1767                         if (sound->newpackedfile) {
1768                                 pf = sound->newpackedfile;
1769                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1770                                 writedata(wd, DATA, pf->size, pf->data);
1771                         }
1772
1773                         if (sample) {
1774                                 sound->newpackedfile = sample->packedfile;
1775                         }
1776                 }
1777                 sound= sound->id.next;
1778         }
1779
1780         /* flush helps the compression for undo-save */
1781         mywrite(wd, MYWRITE_FLUSH, 0);
1782 }
1783
1784 static void write_groups(WriteData *wd, ListBase *idbase)
1785 {
1786         Group *group;
1787         GroupObject *go;
1788
1789         for(group= idbase->first; group; group= group->id.next) {
1790                 if(group->id.us>0 || wd->current) {
1791                         /* write LibData */
1792                         writestruct(wd, ID_GR, "Group", 1, group);
1793                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
1794
1795                         go= group->gobject.first;
1796                         while(go) {
1797                                 writestruct(wd, DATA, "GroupObject", 1, go);
1798                                 go= go->next;
1799                         }
1800                 }
1801         }
1802 }
1803
1804 static void write_nodetrees(WriteData *wd, ListBase *idbase)
1805 {
1806         bNodeTree *ntree;
1807         
1808         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
1809                 if (ntree->id.us>0 || wd->current) {
1810                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
1811                         write_nodetree(wd, ntree);
1812                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
1813                 }
1814         }
1815 }
1816
1817 static void write_brushes(WriteData *wd, ListBase *idbase)
1818 {
1819         Brush *brush;
1820         int a;
1821         
1822         for(brush=idbase->first; brush; brush= brush->id.next) {
1823                 if(brush->id.us>0 || wd->current) {
1824                         writestruct(wd, ID_BR, "Brush", 1, brush);
1825                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
1826                         for(a=0; a<MAX_MTEX; a++)
1827                                 if(brush->mtex[a])
1828                                         writestruct(wd, DATA, "MTex", 1, brush->mtex[a]);
1829                 }
1830         }
1831 }
1832
1833 static void write_global(WriteData *wd)
1834 {
1835         FileGlobal fg;
1836         char subvstr[8];
1837         
1838         fg.curscreen= G.curscreen;
1839         fg.curscene= G.scene;
1840         fg.displaymode= G.displaymode;
1841         fg.winpos= G.winpos;
1842         fg.fileflags= (G.fileflags & ~G_FILE_NO_UI);    // prevent to save this, is not good convention, and feature with concerns...
1843         fg.globalf= G.f;
1844
1845         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
1846         memcpy(fg.subvstr, subvstr, 4);
1847         
1848         fg.subversion= BLENDER_SUBVERSION;
1849         fg.minversion= BLENDER_MINVERSION;
1850         fg.minsubversion= BLENDER_MINSUBVERSION;
1851         
1852         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
1853 }
1854
1855 /* if MemFile * there's filesave to memory */
1856 static int write_file_handle(int handle, MemFile *compare, MemFile *current, int write_user_block, int write_flags)
1857 {
1858         BHead bhead;
1859         ListBase mainlist;
1860         char buf[16];
1861         WriteData *wd;
1862
1863         blo_split_main(&mainlist, G.main);
1864
1865         wd= bgnwrite(handle, compare, current, write_flags);
1866         
1867         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (G.order==B_ENDIAN)?'V':'v', G.version);
1868         mywrite(wd, buf, 12);
1869
1870         write_renderinfo(wd);
1871         write_global(wd);
1872
1873         if(current==NULL)
1874                 write_screens  (wd, &G.main->screen);   /* no UI save in undo */
1875         write_scenes   (wd, &G.main->scene);
1876         write_curves   (wd, &G.main->curve);
1877         write_mballs   (wd, &G.main->mball);
1878         write_images   (wd, &G.main->image);
1879         write_cameras  (wd, &G.main->camera);
1880         write_lamps    (wd, &G.main->lamp);
1881         write_lattices (wd, &G.main->latt);
1882         write_vfonts   (wd, &G.main->vfont);
1883         write_ipos     (wd, &G.main->ipo);
1884         write_keys     (wd, &G.main->key);
1885         write_worlds   (wd, &G.main->world);
1886         write_texts    (wd, &G.main->text);
1887         write_sounds   (wd, &G.main->sound);
1888         write_groups   (wd, &G.main->group);
1889         write_armatures(wd, &G.main->armature);
1890         write_actions  (wd, &G.main->action);
1891         write_objects  (wd, &G.main->object);
1892         write_materials(wd, &G.main->mat);
1893         write_textures (wd, &G.main->tex);
1894         write_meshs    (wd, &G.main->mesh);
1895         write_nodetrees(wd, &G.main->nodetree);
1896         write_brushes  (wd, &G.main->brush);
1897         if(current==NULL)       
1898                 write_libraries(wd,  G.main->next); /* no library save in undo */
1899
1900         if (write_user_block) {
1901                 write_userdef(wd);
1902         }
1903
1904         /* dna as last, because (to be implemented) test for which structs are written */
1905         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
1906
1907         /* end of file */
1908         memset(&bhead, 0, sizeof(BHead));
1909         bhead.code= ENDB;
1910         mywrite(wd, &bhead, sizeof(BHead));
1911
1912         blo_join_main(&mainlist);
1913         G.main= mainlist.first;
1914
1915         return endwrite(wd);
1916 }
1917
1918 /* return: success (1) */
1919 int BLO_write_file(char *dir, int write_flags, char **error_r)
1920 {
1921         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
1922         char tempname[FILE_MAXDIR+FILE_MAXFILE];
1923         int file, err, write_user_block;
1924
1925         sprintf(tempname, "%s@", dir);
1926
1927         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
1928         if(file == -1) {
1929                 *error_r= "Unable to open";
1930                 return 0;
1931         }
1932
1933         BLI_make_file_string(G.sce, userfilename, BLI_gethome(), ".B.blend");
1934
1935         write_user_block= BLI_streq(dir, userfilename);
1936
1937         err= write_file_handle(file, NULL,NULL, write_user_block, write_flags);
1938         close(file);
1939
1940         if(!err) {
1941                 if(write_flags & G_FILE_COMPRESS)
1942                 {       
1943                         // compressed files have the same ending as regular files... only from 2.4!!!
1944                         
1945                         int ret = BLI_gzip(tempname, dir);
1946                         
1947                         if(-1==ret) {
1948                                 *error_r= "Failed opening .gz file";
1949                                 return 0;
1950                         }
1951                         if(-2==ret) {
1952                                 *error_r= "Failed opening .blend file for compression";
1953                                 return 0;
1954                         }
1955                 }
1956                 else
1957                 if(BLI_rename(tempname, dir) < 0) {
1958                         *error_r= "Can't change old file. File saved with @";
1959                         return 0;
1960                 }
1961
1962                 
1963         } else {
1964                 *error_r= strerror(errno);
1965                 remove(tempname);
1966
1967                 return 0;
1968         }
1969
1970         return 1;
1971 }
1972
1973 /* return: success (1) */
1974 int BLO_write_file_mem(MemFile *compare, MemFile *current, int write_flags, char **error_r)
1975 {
1976         int err;
1977
1978         err= write_file_handle(0, compare, current, 0, write_flags);
1979         
1980         if(err==0) return 1;
1981         return 0;
1982 }
1983
1984
1985         /* Runtime writing */
1986
1987 #ifdef WIN32
1988 #define PATHSEPERATOR           "\\"
1989 #else
1990 #define PATHSEPERATOR           "/"
1991 #endif
1992
1993 static char *get_install_dir(void) {
1994         extern char bprogname[];
1995         char *tmpname = BLI_strdup(bprogname);
1996         char *cut;
1997
1998 #ifdef __APPLE__
1999         cut = strstr(tmpname, ".app");
2000         if (cut) cut[0] = 0;
2001 #endif
2002
2003         cut = BLI_last_slash(tmpname);
2004
2005         if (cut) {
2006                 cut[0] = 0;
2007                 return tmpname;
2008         } else {
2009                 MEM_freeN(tmpname);
2010                 return NULL;
2011         }
2012 }
2013
2014 static char *get_runtime_path(char *exename) {
2015         char *installpath= get_install_dir();
2016
2017         if (!installpath) {
2018                 return NULL;
2019         } else {
2020                 char *path= MEM_mallocN(strlen(installpath)+strlen(PATHSEPERATOR)+strlen(exename)+1, "runtimepath");
2021
2022                 if (path == NULL) {
2023                         MEM_freeN(installpath);
2024                         return NULL;
2025                 }
2026
2027                 strcpy(path, installpath);
2028                 strcat(path, PATHSEPERATOR);
2029                 strcat(path, exename);
2030
2031                 MEM_freeN(installpath);
2032
2033                 return path;
2034         }
2035 }
2036
2037 #ifdef __APPLE__
2038
2039 static int recursive_copy_runtime(char *outname, char *exename, char **cause_r) 
2040 {
2041         char *cause = NULL, *runtime = get_runtime_path(exename);
2042         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
2043         int progfd = -1;
2044
2045         if (!runtime) {
2046                 cause= "Unable to find runtime";
2047                 goto cleanup;
2048         }
2049         //printf("runtimepath %s\n", runtime);
2050                 
2051         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2052         if (progfd==-1) {
2053                 cause= "Unable to find runtime";
2054                 goto cleanup;
2055         }
2056
2057         sprintf(command, "/bin/cp -R \"%s\" \"%s\"", runtime, outname);
2058         //printf("command %s\n", command);
2059         if (system(command) == -1) {
2060                 cause = "Couldn't copy runtime";
2061         }
2062
2063 cleanup:
2064         if (progfd!=-1)
2065                 close(progfd);
2066         if (runtime)
2067                 MEM_freeN(runtime);
2068
2069         if (cause) {
2070                 *cause_r= cause;
2071                 return 0;
2072         } else
2073                 return 1;
2074 }
2075
2076 void BLO_write_runtime(char *file, char *exename) {
2077         char gamename[FILE_MAXDIR+FILE_MAXFILE];
2078         int outfd = -1;
2079         char *cause= NULL;
2080
2081         // remove existing file / bundle
2082         //printf("Delete file %s\n", file);
2083         BLI_delete(file, 0, TRUE);
2084
2085         if (!recursive_copy_runtime(file, exename, &cause))
2086                 goto cleanup;
2087
2088         strcpy(gamename, file);
2089         strcat(gamename, "/Contents/Resources/game.blend");
2090         //printf("gamename %s\n", gamename);
2091         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2092         if (outfd != -1) {
2093
2094                 write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
2095
2096                 if (write(outfd, " ", 1) != 1) {
2097                         cause= "Unable to write to output file";
2098                         goto cleanup;
2099                 }
2100         } else {
2101                 cause = "Unable to open blenderfile";
2102         }
2103
2104 cleanup:
2105         if (outfd!=-1)
2106                 close(outfd);
2107
2108         if (cause)
2109                 error("Unable to make runtime: %s", cause);
2110 }
2111
2112 #else /* !__APPLE__ */
2113
2114 static int handle_append_runtime(int handle, char *exename, char **cause_r) {
2115         char *cause= NULL, *runtime= get_runtime_path(exename);
2116         unsigned char buf[1024];
2117         int count, progfd= -1;
2118
2119         if (!runtime) {
2120                 cause= "Unable to find runtime";
2121                 goto cleanup;
2122         }
2123
2124         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2125         if (progfd==-1) {
2126                 cause= "Unable to find runtime";
2127                 goto cleanup;
2128         }
2129
2130         while ((count= read(progfd, buf, sizeof(buf)))>0) {
2131                 if (write(handle, buf, count)!=count) {
2132                         cause= "Unable to write to output file";
2133                         goto cleanup;
2134                 }
2135         }
2136
2137 cleanup:
2138         if (progfd!=-1)
2139                 close(progfd);
2140         if (runtime)
2141                 MEM_freeN(runtime);
2142
2143         if (cause) {
2144                 *cause_r= cause;
2145                 return 0;
2146         } else
2147                 return 1;
2148 }
2149
2150 static int handle_write_msb_int(int handle, int i) {
2151         unsigned char buf[4];
2152         buf[0]= (i>>24)&0xFF;
2153         buf[1]= (i>>16)&0xFF;
2154         buf[2]= (i>>8)&0xFF;
2155         buf[3]= (i>>0)&0xFF;
2156
2157         return (write(handle, buf, 4)==4);
2158 }
2159
2160 void BLO_write_runtime(char *file, char *exename) {
2161         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2162         char *cause= NULL;
2163         int datastart;
2164
2165         if (!outfd) {
2166                 cause= "Unable to open output file";
2167                 goto cleanup;
2168         }
2169         if (!handle_append_runtime(outfd, exename, &cause))
2170                 goto cleanup;
2171
2172         datastart= lseek(outfd, 0, SEEK_CUR);
2173
2174         write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
2175
2176         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
2177                 cause= "Unable to write to output file";
2178                 goto cleanup;
2179         }
2180
2181 cleanup:
2182         if (outfd!=-1)
2183                 close(outfd);
2184
2185         if (cause)
2186                 error("Unable to make runtime: %s", cause);
2187 }
2188
2189 #endif /* !__APPLE__ */