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