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