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