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