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