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