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