Temporary fix for loading crash of .blends with cached frames. Also fixed some goal...
[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_cloth_types.h"
111 #include "DNA_color_types.h"
112 #include "DNA_constraint_types.h"
113 #include "DNA_controller_types.h"
114 #include "DNA_curve_types.h"
115 #include "DNA_customdata_types.h"
116 #include "DNA_effect_types.h"
117 #include "DNA_group_types.h"
118 #include "DNA_image_types.h"
119 #include "DNA_ipo_types.h"
120 #include "DNA_fileglobal_types.h"
121 #include "DNA_key_types.h"
122 #include "DNA_lattice_types.h"
123 #include "DNA_listBase.h" /* for Listbase, the type of samples, ...*/
124 #include "DNA_lamp_types.h"
125 #include "DNA_meta_types.h"
126 #include "DNA_mesh_types.h"
127 #include "DNA_meshdata_types.h"
128 #include "DNA_material_types.h"
129 #include "DNA_modifier_types.h"
130 #include "DNA_nla_types.h"
131 #include "DNA_node_types.h"
132 #include "DNA_object_types.h"
133 #include "DNA_object_force.h"
134 #include "DNA_oops_types.h"
135 #include "DNA_packedFile_types.h"
136 #include "DNA_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_cloth.h"
159 #include "BKE_curve.h"
160 #include "BKE_customdata.h"
161 #include "BKE_constraint.h"
162 #include "BKE_global.h" // for G
163 #include "BKE_library.h" // for  set_listbasepointers
164 #include "BKE_main.h" // G.main
165 #include "BKE_node.h"
166 #include "BKE_packedFile.h" // for packAll
167 #include "BKE_screen.h" // for waitcursor
168 #include "BKE_scene.h" // for do_seq
169 #include "BKE_sound.h" /* ... and for samples */
170 #include "BKE_utildefines.h" // for defines
171 #include "BKE_modifier.h"
172 #include "BKE_idprop.h"
173 #ifdef WITH_VERSE
174 #include "BKE_verse.h"
175 #include "BIF_verse.h"
176 #endif
177
178 #include "GEN_messaging.h"
179
180 #include "BLO_writefile.h"
181 #include "BLO_readfile.h"
182 #include "BLO_undofile.h"
183
184 #include "readfile.h"
185 #include "genfile.h"
186
187 #include <errno.h>
188
189 /* ********* my write, buffered writing with minimum 50k chunks ************ */
190
191 typedef struct {
192         struct SDNA *sdna;
193
194         int file;
195         unsigned char *buf;
196         MemFile *compare, *current;
197         
198         int tot, count, error, memsize;
199 } WriteData;
200
201 static WriteData *writedata_new(int file)
202 {
203         extern unsigned char DNAstr[];  /* DNA.c */
204         extern int DNAlen;
205
206         WriteData *wd= MEM_callocN(sizeof(*wd), "writedata");
207
208                 /* XXX, see note about this in readfile.c, remove
209                  * once we have an xp lock - zr
210                  */
211
212         if (wd == NULL) return NULL;
213
214         wd->sdna= dna_sdna_from_data(DNAstr, DNAlen, 0);
215
216         wd->file= file;
217
218         wd->buf= MEM_mallocN(100000, "wd->buf");
219
220         return wd;
221 }
222
223 static void writedata_do_write(WriteData *wd, void *mem, int memlen)
224 {
225         if ((wd == NULL) || wd->error || (mem == NULL) || memlen < 1) return;
226         if (wd->error) return;
227
228         /* memory based save */
229         if(wd->current) {
230                 add_memfilechunk(NULL, wd->current, mem, memlen);
231         }
232         else {
233                 if (write(wd->file, mem, memlen) != memlen)
234                         wd->error= 1;
235                 
236         }
237 }
238
239 static void writedata_free(WriteData *wd)
240 {
241         dna_freestructDNA(wd->sdna);
242
243         MEM_freeN(wd->buf);
244         MEM_freeN(wd);
245 }
246
247 /***/
248
249 int mywfile;
250
251 /**
252  * Low level WRITE(2) wrapper that buffers data
253  * @param adr Pointer to new chunk of data
254  * @param len Length of new chunk of data
255  * @warning Talks to other functions with global parameters
256  */
257  
258 #define MYWRITE_FLUSH   NULL
259
260 static void mywrite( WriteData *wd, void *adr, int len)
261 {
262         if (wd->error) return;
263
264         if(adr==MYWRITE_FLUSH) {
265                 if(wd->count) {
266                         writedata_do_write(wd, wd->buf, wd->count);
267                         wd->count= 0;
268                 }
269                 return;
270         }
271
272         wd->tot+= len;
273         
274         if(len>50000) {
275                 if(wd->count) {
276                         writedata_do_write(wd, wd->buf, wd->count);
277                         wd->count= 0;
278                 }
279                 writedata_do_write(wd, adr, len);
280                 return;
281         }
282         if(len+wd->count>99999) {
283                 writedata_do_write(wd, wd->buf, wd->count);
284                 wd->count= 0;
285         }
286         memcpy(&wd->buf[wd->count], adr, len);
287         wd->count+= len;
288
289 }
290
291 /**
292  * BeGiN initializer for mywrite
293  * @param file File descriptor
294  * @param write_flags Write parameters
295  * @warning Talks to other functions with global parameters
296  */
297 static WriteData *bgnwrite(int file, MemFile *compare, MemFile *current, int write_flags)
298 {
299         WriteData *wd= writedata_new(file);
300
301         if (wd == NULL) return NULL;
302
303         wd->compare= compare;
304         wd->current= current;
305         /* this inits comparing */
306         add_memfilechunk(compare, NULL, NULL, 0);
307         
308         return wd;
309 }
310
311 /**
312  * END the mywrite wrapper
313  * @return 1 if write failed
314  * @return unknown global variable otherwise
315  * @warning Talks to other functions with global parameters
316  */
317 static int endwrite(WriteData *wd)
318 {
319         int err;
320
321         if (wd->count) {
322                 writedata_do_write(wd, wd->buf, wd->count);
323                 wd->count= 0;
324         }
325         
326         err= wd->error;
327         writedata_free(wd);
328
329         return err;
330 }
331
332 /* ********** WRITE FILE ****************** */
333
334 static void writestruct(WriteData *wd, int filecode, char *structname, int nr, void *adr)
335 {
336         BHead bh;
337         short *sp;
338
339         if(adr==NULL || nr==0) return;
340
341         /* init BHead */
342         bh.code= filecode;
343         bh.old= adr;
344         bh.nr= nr;
345
346         bh.SDNAnr= dna_findstruct_nr(wd->sdna, structname);
347         if(bh.SDNAnr== -1) {
348                 printf("error: can't find SDNA code <%s>\n", structname);
349                 return;
350         }
351         sp= wd->sdna->structs[bh.SDNAnr];
352
353         bh.len= nr*wd->sdna->typelens[sp[0]];
354
355         if(bh.len==0) return;
356
357         mywrite(wd, &bh, sizeof(BHead));
358         mywrite(wd, adr, bh.len);
359 }
360
361 static void writedata(WriteData *wd, int filecode, int len, void *adr)  /* do not use for structs */
362 {
363         BHead bh;
364
365         if(adr==0) return;
366         if(len==0) return;
367
368         len+= 3;
369         len-= ( len % 4);
370
371         /* init BHead */
372         bh.code= filecode;
373         bh.old= adr;
374         bh.nr= 1;
375         bh.SDNAnr= 0;
376         bh.len= len;
377
378         mywrite(wd, &bh, sizeof(BHead));
379         if(len) mywrite(wd, adr, len);
380 }
381
382 /* *************** writing some direct data structs used in more code parts **************** */
383 /*These functions are used by blender's .blend system for file saving/loading.*/
384 void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd);
385 void IDP_WriteProperty(IDProperty *prop, void *wd);
386
387 void IDP_WriteArray(IDProperty *prop, void *wd)
388 {
389         /*REMEMBER to set totalen to len in the linking code!!*/
390         if (prop->data.pointer) {
391                 writedata(wd, DATA, MEM_allocN_len(prop->data.pointer), prop->data.pointer);
392         }
393 }
394
395 void IDP_WriteString(IDProperty *prop, void *wd)
396 {
397         /*REMEMBER to set totalen to len in the linking code!!*/
398         writedata(wd, DATA, prop->len+1, prop->data.pointer);
399 }
400
401 void IDP_WriteGroup(IDProperty *prop, void *wd)
402 {
403         IDProperty *loop;
404
405         for (loop=prop->data.group.first; loop; loop=loop->next) {
406                 IDP_WriteProperty(loop, wd);
407         }
408 }
409
410 /* Functions to read/write ID Properties */
411 void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd)
412 {
413         switch (prop->type) {
414                 case IDP_GROUP:
415                         IDP_WriteGroup(prop, wd);
416                         break;
417                 case IDP_STRING:
418                         IDP_WriteString(prop, wd);
419                         break;
420                 case IDP_ARRAY:
421                         IDP_WriteArray(prop, wd);
422                         break;
423         }
424 }
425
426 void IDP_WriteProperty(IDProperty *prop, void *wd)
427 {
428         writestruct(wd, DATA, "IDProperty", 1, prop);
429         IDP_WriteProperty_OnlyData(prop, wd);
430 }
431
432 static void write_curvemapping(WriteData *wd, CurveMapping *cumap)
433 {
434         int a;
435         
436         writestruct(wd, DATA, "CurveMapping", 1, cumap);
437         for(a=0; a<CM_TOT; a++)
438                 writestruct(wd, DATA, "CurveMapPoint", cumap->cm[a].totpoint, cumap->cm[a].curve);
439 }
440
441 /* this is only direct data, tree itself should have been written */
442 static void write_nodetree(WriteData *wd, bNodeTree *ntree)
443 {
444         bNode *node;
445         bNodeSocket *sock;
446         bNodeLink *link;
447         
448         /* for link_list() speed, we write per list */
449         
450         for(node= ntree->nodes.first; node; node= node->next)
451                 writestruct(wd, DATA, "bNode", 1, node);
452
453         for(node= ntree->nodes.first; node; node= node->next) {
454                 if(node->storage) {
455                         /* could be handlerized at some point, now only 1 exception still */
456                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
457                                 write_curvemapping(wd, node->storage);
458                         else if(ntree->type==NTREE_COMPOSIT && (node->type==CMP_NODE_TIME || node->type==CMP_NODE_CURVE_VEC || node->type==CMP_NODE_CURVE_RGB))
459                                 write_curvemapping(wd, node->storage);
460                         else 
461                                 writestruct(wd, DATA, node->typeinfo->storagename, 1, node->storage);
462                 }
463                 for(sock= node->inputs.first; sock; sock= sock->next)
464                         writestruct(wd, DATA, "bNodeSocket", 1, sock);
465                 for(sock= node->outputs.first; sock; sock= sock->next)
466                         writestruct(wd, DATA, "bNodeSocket", 1, sock);
467         }
468         
469         for(link= ntree->links.first; link; link= link->next)
470                 writestruct(wd, DATA, "bNodeLink", 1, link);
471 }
472
473 static void write_scriptlink(WriteData *wd, ScriptLink *slink)
474 {
475         writedata(wd, DATA, sizeof(void *)*slink->totscript, slink->scripts);
476         writedata(wd, DATA, sizeof(short)*slink->totscript, slink->flag);
477 }
478
479 static void write_renderinfo(WriteData *wd)             /* for renderdeamon */
480 {
481         Scene *sce;
482         int data[8];
483
484         sce= G.main->scene.first;
485         while(sce) {
486                 if(sce->id.lib==0  && ( sce==G.scene || (sce->r.scemode & R_BG_RENDER)) ) {
487                         data[0]= sce->r.sfra;
488                         data[1]= sce->r.efra;
489
490                         memset(data+2, 0, sizeof(int)*6);
491                         strncpy((char *)(data+2), sce->id.name+2, 21);
492
493                         writedata(wd, REND, 32, data);
494                 }
495                 sce= sce->id.next;
496         }
497 }
498
499 static void write_userdef(WriteData *wd)
500 {
501         bTheme *btheme;
502
503         writestruct(wd, USER, "UserDef", 1, &U);
504
505         btheme= U.themes.first;
506         while(btheme) {
507                 writestruct(wd, DATA, "bTheme", 1, btheme);
508                 btheme= btheme->next;
509         }
510 }
511
512 static void write_effects(WriteData *wd, ListBase *lb)
513 {
514         Effect *eff;
515
516         eff= lb->first;
517         while(eff) {
518
519                 switch(eff->type) {
520                 case EFF_PARTICLE:
521                         writestruct(wd, DATA, "PartEff", 1, eff);
522                         break;
523                 default:
524                         writedata(wd, DATA, MEM_allocN_len(eff), eff);
525                 }
526
527                 eff= eff->next;
528         }
529 }
530
531 static void write_properties(WriteData *wd, ListBase *lb)
532 {
533         bProperty *prop;
534
535         prop= lb->first;
536         while(prop) {
537                 writestruct(wd, DATA, "bProperty", 1, prop);
538
539                 if(prop->poin && prop->poin != &prop->data)
540                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
541
542                 prop= prop->next;
543         }
544 }
545
546 static void write_sensors(WriteData *wd, ListBase *lb)
547 {
548         bSensor *sens;
549
550         sens= lb->first;
551         while(sens) {
552                 writestruct(wd, DATA, "bSensor", 1, sens);
553
554                 writedata(wd, DATA, sizeof(void *)*sens->totlinks, sens->links);
555
556                 switch(sens->type) {
557                 case SENS_NEAR:
558                         writestruct(wd, DATA, "bNearSensor", 1, sens->data);
559                         break;
560                 case SENS_MOUSE:
561                         writestruct(wd, DATA, "bMouseSensor", 1, sens->data);
562                         break;
563                 case SENS_TOUCH:
564                         writestruct(wd, DATA, "bTouchSensor", 1, sens->data);
565                         break;
566                 case SENS_KEYBOARD:
567                         writestruct(wd, DATA, "bKeyboardSensor", 1, sens->data);
568                         break;
569                 case SENS_PROPERTY:
570                         writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
571                         break;
572                 case SENS_COLLISION:
573                         writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
574                         break;
575                 case SENS_RADAR:
576                         writestruct(wd, DATA, "bRadarSensor", 1, sens->data);
577                         break;
578                 case SENS_RANDOM:
579                         writestruct(wd, DATA, "bRandomSensor", 1, sens->data);
580                         break;
581                 case SENS_RAY:
582                         writestruct(wd, DATA, "bRaySensor", 1, sens->data);
583                         break;
584                 case SENS_MESSAGE:
585                         writestruct(wd, DATA, "bMessageSensor", 1, sens->data);
586                         break;
587                 case SENS_JOYSTICK:
588                         writestruct(wd, DATA, "bJoystickSensor", 1, sens->data);
589                         break;
590                 default:
591                         ; /* error: don't know how to write this file */
592                 }
593
594                 sens= sens->next;
595         }
596 }
597
598 static void write_controllers(WriteData *wd, ListBase *lb)
599 {
600         bController *cont;
601
602         cont= lb->first;
603         while(cont) {
604                 writestruct(wd, DATA, "bController", 1, cont);
605
606                 writedata(wd, DATA, sizeof(void *)*cont->totlinks, cont->links);
607
608                 switch(cont->type) {
609                 case CONT_EXPRESSION:
610                         writestruct(wd, DATA, "bExpressionCont", 1, cont->data);
611                         break;
612                 case CONT_PYTHON:
613                         writestruct(wd, DATA, "bPythonCont", 1, cont->data);
614                         break;
615                 default:
616                         ; /* error: don't know how to write this file */
617                 }
618
619                 cont= cont->next;
620         }
621 }
622
623 static void write_actuators(WriteData *wd, ListBase *lb)
624 {
625         bActuator *act;
626
627         act= lb->first;
628         while(act) {
629                 writestruct(wd, DATA, "bActuator", 1, act);
630
631                 switch(act->type) {
632                 case ACT_ACTION:
633                         writestruct(wd, DATA, "bActionActuator", 1, act->data);
634                         break;
635                 case ACT_SOUND:
636                         writestruct(wd, DATA, "bSoundActuator", 1, act->data);
637                         break;
638                 case ACT_CD:
639                         writestruct(wd, DATA, "bCDActuator", 1, act->data);
640                         break;
641                 case ACT_OBJECT:
642                         writestruct(wd, DATA, "bObjectActuator", 1, act->data);
643                         break;
644                 case ACT_IPO:
645                         writestruct(wd, DATA, "bIpoActuator", 1, act->data);
646                         break;
647                 case ACT_PROPERTY:
648                         writestruct(wd, DATA, "bPropertyActuator", 1, act->data);
649                         break;
650                 case ACT_CAMERA:
651                         writestruct(wd, DATA, "bCameraActuator", 1, act->data);
652                         break;
653                 case ACT_CONSTRAINT:
654                         writestruct(wd, DATA, "bConstraintActuator", 1, act->data);
655                         break;
656                 case ACT_EDIT_OBJECT:
657                         writestruct(wd, DATA, "bEditObjectActuator", 1, act->data);
658                         break;
659                 case ACT_SCENE:
660                         writestruct(wd, DATA, "bSceneActuator", 1, act->data);
661                         break;
662                 case ACT_GROUP:
663                         writestruct(wd, DATA, "bGroupActuator", 1, act->data);
664                         break;
665                 case ACT_RANDOM:
666                         writestruct(wd, DATA, "bRandomActuator", 1, act->data);
667                         break;
668                 case ACT_MESSAGE:
669                         writestruct(wd, DATA, "bMessageActuator", 1, act->data);
670                         break;
671                 case ACT_GAME:
672                         writestruct(wd, DATA, "bGameActuator", 1, act->data);
673                         break;
674                 case ACT_VISIBILITY:
675                         writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
676                         break;
677                 default:
678                         ; /* error: don't know how to write this file */
679                 }
680
681                 act= act->next;
682         }
683 }
684
685 static void write_nlastrips(WriteData *wd, ListBase *nlabase)
686 {
687         bActionStrip *strip;
688         bActionModifier *amod;
689         
690         for (strip=nlabase->first; strip; strip=strip->next)
691                 writestruct(wd, DATA, "bActionStrip", 1, strip);
692         for (strip=nlabase->first; strip; strip=strip->next) {
693                 for(amod= strip->modifiers.first; amod; amod= amod->next)
694                         writestruct(wd, DATA, "bActionModifier", 1, amod);
695         }
696 }
697
698 static void write_constraints(WriteData *wd, ListBase *conlist)
699 {
700         bConstraint *con;
701
702         for (con=conlist->first; con; con=con->next) {
703                 /* Write the specific data */
704                 switch (con->type) {
705                 case CONSTRAINT_TYPE_NULL:
706                         break;
707                 case CONSTRAINT_TYPE_PYTHON:
708                         {
709                                 bPythonConstraint *data = (bPythonConstraint*) con->data;
710                                 writestruct(wd, DATA, "bPythonConstraint", 1, data);
711                                 
712                                 /* Write ID Properties -- and copy this comment EXACTLY for easy finding
713                                  of library blocks that implement this.*/
714                                 IDP_WriteProperty(data->prop, wd);
715                         }
716                         break;
717                 case CONSTRAINT_TYPE_CHILDOF:
718                         writestruct(wd, DATA, "bChildOfConstraint", 1, con->data);
719                         break;
720                 case CONSTRAINT_TYPE_TRACKTO:
721                         writestruct(wd, DATA, "bTrackToConstraint", 1, con->data);
722                         break;
723                 case CONSTRAINT_TYPE_KINEMATIC:
724                         writestruct(wd, DATA, "bKinematicConstraint", 1, con->data);
725                         break;
726                 case CONSTRAINT_TYPE_ROTLIKE:
727                         writestruct(wd, DATA, "bRotateLikeConstraint", 1, con->data);
728                         break;
729                 case CONSTRAINT_TYPE_LOCLIKE:
730                         writestruct(wd, DATA, "bLocateLikeConstraint", 1, con->data);
731                         break;
732                 case CONSTRAINT_TYPE_SIZELIKE:
733                         writestruct(wd, DATA, "bSizeLikeConstraint", 1, con->data);
734                         break;
735                 case CONSTRAINT_TYPE_ACTION:
736                         writestruct(wd, DATA, "bActionConstraint", 1, con->data);
737                         break;
738                 case CONSTRAINT_TYPE_LOCKTRACK:
739                         writestruct(wd, DATA, "bLockTrackConstraint", 1, con->data);
740                         break;
741                 case CONSTRAINT_TYPE_FOLLOWPATH:
742                         writestruct(wd, DATA, "bFollowPathConstraint", 1, con->data);
743                         break;
744                 case CONSTRAINT_TYPE_STRETCHTO:
745                         writestruct(wd, DATA, "bStretchToConstraint", 1, con->data);
746                         break;
747                 case CONSTRAINT_TYPE_MINMAX:
748                         writestruct(wd, DATA, "bMinMaxConstraint", 1, con->data);
749                         break;
750                 case CONSTRAINT_TYPE_LOCLIMIT:
751                         writestruct(wd, DATA, "bLocLimitConstraint", 1, con->data);
752                         break;
753                 case CONSTRAINT_TYPE_ROTLIMIT:
754                         writestruct(wd, DATA, "bRotLimitConstraint", 1, con->data);
755                         break;
756                 case CONSTRAINT_TYPE_SIZELIMIT:
757                         writestruct(wd, DATA, "bSizeLimitConstraint", 1, con->data);
758                         break;
759                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
760                         writestruct(wd, DATA, "bRigidBodyJointConstraint", 1, con->data);
761                         break;
762                 case CONSTRAINT_TYPE_CLAMPTO:
763                         writestruct(wd, DATA, "bClampToConstraint", 1, con->data);
764                         break;
765                 case CONSTRAINT_TYPE_TRANSFORM:
766                         writestruct(wd, DATA, "bTransformConstraint", 1, con->data);
767                         break;
768                 default:
769                         break;
770                 }
771                 /* Write the constraint */
772                 writestruct(wd, DATA, "bConstraint", 1, con);
773         }
774 }
775
776 static void write_pose(WriteData *wd, bPose *pose)
777 {
778         bPoseChannel *chan;
779
780         /* Write each channel */
781         if (!pose)
782                 return;
783
784         /* Write channels */
785         for (chan=pose->chanbase.first; chan; chan=chan->next) {
786                 write_constraints(wd, &chan->constraints);
787                 
788                 /* prevent crashes with autosave, when a bone duplicated in editmode has not yet been assigned to its posechannel */
789                 if (chan->bone) 
790                         chan->selectflag= chan->bone->flag & (BONE_SELECTED|BONE_ACTIVE); /* gets restored on read, for library armatures */
791                 
792                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
793         }
794
795         /* Write this pose */
796         writestruct(wd, DATA, "bPose", 1, pose);
797 }
798
799 static void write_defgroups(WriteData *wd, ListBase *defbase)
800 {
801         bDeformGroup    *defgroup;
802
803         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
804                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
805 }
806
807 static void write_constraint_channels(WriteData *wd, ListBase *chanbase)
808 {
809         bConstraintChannel *chan;
810
811         for (chan = chanbase->first; chan; chan=chan->next)
812                 writestruct(wd, DATA, "bConstraintChannel", 1, chan);
813
814 }
815
816 /*
817 // TODO: finish this
818 static void write_cloth_cache(WriteData *wd, LinkNode *ln)
819 {
820         
821         while(ln) {
822                 writestruct(wd, DATA, "cloth_cache", 1, ln);            
823                 writestruct(wd, DATA, "cloth_cache_frame", 1, ln->link);
824                 writestruct(wd, DATA, "cloth_cache_frame_verts", 1, ln->link);
825                 writestruct(wd, DATA, "cloth_cache_frame_springs", 1, ln->link);
826                 }
827
828                 ln = ln->next;
829         }
830 }
831 */
832                 
833 static void write_modifiers(WriteData *wd, ListBase *modbase)
834 {
835         ModifierData *md;
836
837         if (modbase == NULL) return;
838         for (md=modbase->first; md; md= md->next) {
839                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
840                 if (mti == NULL) return;
841
842                 writestruct(wd, DATA, mti->structName, 1, md);
843
844                 if (md->type==eModifierType_Hook) {
845                         HookModifierData *hmd = (HookModifierData*) md;
846
847                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
848         }
849         else if (md->type==eModifierType_Cloth) {
850                    int                                  n;
851                    ClothModifierData    *clmd = (ClothModifierData *) md;
852
853                    if (clmd->sim_parms.cache) {
854                           // Compute the number of vertices we're saving.
855                            // TODO
856                            // write_cloth_cache();
857                           /*
858                            // old code
859                           n = (clmd->sim_parms.bake_end_frame - clmd->sim_parms.bake_start_frame + 1) *
860                                  clmd->sim_parms.bake_num_verts;
861                           writedata (wd, DATA, n *  sizeof (clmd->baked_data [0]), clmd->baked_data);
862                           printf ("write_modifiers: wrote %d elements of size %d for cloth baked data.\n",
863                                           n, sizeof (clmd->baked_data [0]));
864                            */
865                    }
866                 }
867         }
868 }
869
870 static void write_objects(WriteData *wd, ListBase *idbase)
871 {
872         Object *ob;
873         int a;
874         
875         ob= idbase->first;
876         while(ob) {
877                 if(ob->id.us>0 || wd->current) {
878                         /* write LibData */
879 #ifdef WITH_VERSE
880                         /* pointer at vnode stored in file have to be NULL */
881                         struct VNode *vnode = (VNode*)ob->vnode;
882                         if(vnode) ob->vnode = NULL;
883 #endif
884                         writestruct(wd, ID_OB, "Object", 1, ob);
885 #ifdef WITH_VERSE
886                         if(vnode) ob->vnode = (void*)vnode;
887 #endif
888
889                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
890                           of library blocks that implement this.*/
891                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
892
893                         /* direct data */
894                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
895                         write_effects(wd, &ob->effect);
896                         write_properties(wd, &ob->prop);
897                         write_sensors(wd, &ob->sensors);
898                         write_controllers(wd, &ob->controllers);
899                         write_actuators(wd, &ob->actuators);
900                         write_scriptlink(wd, &ob->scriptlink);
901                         write_pose(wd, ob->pose);
902                         write_defgroups(wd, &ob->defbase);
903                         write_constraints(wd, &ob->constraints);
904                         write_constraint_channels(wd, &ob->constraintChannels);
905                         write_nlastrips(wd, &ob->nlastrips);
906                         
907                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
908                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
909                         if(ob->soft) {
910                                 SoftBody *sb= ob->soft;
911                                 if(sb->keys) {
912                                         writedata(wd, DATA, sizeof(void *)*sb->totkey, sb->keys);
913                                         for(a=0; a<sb->totkey; a++) {
914                                                 writestruct(wd, DATA, "SBVertex", sb->totpoint, sb->keys[a]);
915                                         }
916                                 }
917                         }
918                         writestruct(wd, DATA, "FluidsimSettings", 1, ob->fluidsimSettings); // NT
919                         
920                         write_modifiers(wd, &ob->modifiers);
921                 }
922                 ob= ob->id.next;
923         }
924
925         /* flush helps the compression for undo-save */
926         mywrite(wd, MYWRITE_FLUSH, 0);
927 }
928
929
930 static void write_vfonts(WriteData *wd, ListBase *idbase)
931 {
932         VFont *vf;
933         PackedFile * pf;
934
935         vf= idbase->first;
936         while(vf) {
937                 if(vf->id.us>0 || wd->current) {
938                         /* write LibData */
939                         writestruct(wd, ID_VF, "VFont", 1, vf);
940                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
941
942                         /* direct data */
943
944                         if (vf->packedfile) {
945                                 pf = vf->packedfile;
946                                 writestruct(wd, DATA, "PackedFile", 1, pf);
947                                 writedata(wd, DATA, pf->size, pf->data);
948                         }
949                 }
950
951                 vf= vf->id.next;
952         }
953 }
954
955 static void write_ipos(WriteData *wd, ListBase *idbase)
956 {
957         Ipo *ipo;
958         IpoCurve *icu;
959
960         ipo= idbase->first;
961         while(ipo) {
962                 if(ipo->id.us>0 || wd->current) {
963                         /* write LibData */
964                         writestruct(wd, ID_IP, "Ipo", 1, ipo);
965                         if (ipo->id.properties) IDP_WriteProperty(ipo->id.properties, wd);
966
967                         /* direct data */
968                         icu= ipo->curve.first;
969                         while(icu) {
970                                 writestruct(wd, DATA, "IpoCurve", 1, icu);
971                                 icu= icu->next;
972                         }
973
974                         icu= ipo->curve.first;
975                         while(icu) {
976                                 if(icu->bezt)  writestruct(wd, DATA, "BezTriple", icu->totvert, icu->bezt);
977                                 if(icu->bp)  writestruct(wd, DATA, "BPoint", icu->totvert, icu->bp);
978                                 if(icu->driver)  writestruct(wd, DATA, "IpoDriver", 1, icu->driver);
979                                 icu= icu->next;
980                         }
981                 }
982
983                 ipo= ipo->id.next;
984         }
985
986         /* flush helps the compression for undo-save */
987         mywrite(wd, MYWRITE_FLUSH, 0);
988 }
989
990 static void write_keys(WriteData *wd, ListBase *idbase)
991 {
992         Key *key;
993         KeyBlock *kb;
994
995         key= idbase->first;
996         while(key) {
997                 if(key->id.us>0 || wd->current) {
998                         /* write LibData */
999                         writestruct(wd, ID_KE, "Key", 1, key);
1000                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
1001
1002                         /* direct data */
1003                         kb= key->block.first;
1004                         while(kb) {
1005                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
1006                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
1007                                 kb= kb->next;
1008                         }
1009                 }
1010
1011                 key= key->id.next;
1012         }
1013         /* flush helps the compression for undo-save */
1014         mywrite(wd, MYWRITE_FLUSH, 0);
1015 }
1016
1017 static void write_cameras(WriteData *wd, ListBase *idbase)
1018 {
1019         Camera *cam;
1020
1021         cam= idbase->first;
1022         while(cam) {
1023                 if(cam->id.us>0 || wd->current) {
1024                         /* write LibData */
1025                         writestruct(wd, ID_CA, "Camera", 1, cam);
1026                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
1027
1028                         /* direct data */
1029                         write_scriptlink(wd, &cam->scriptlink);
1030                 }
1031
1032                 cam= cam->id.next;
1033         }
1034 }
1035
1036 static void write_mballs(WriteData *wd, ListBase *idbase)
1037 {
1038         MetaBall *mb;
1039         MetaElem *ml;
1040
1041         mb= idbase->first;
1042         while(mb) {
1043                 if(mb->id.us>0 || wd->current) {
1044                         /* write LibData */
1045                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
1046                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
1047
1048                         /* direct data */
1049                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
1050
1051                         ml= mb->elems.first;
1052                         while(ml) {
1053                                 writestruct(wd, DATA, "MetaElem", 1, ml);
1054                                 ml= ml->next;
1055                         }
1056                 }
1057                 mb= mb->id.next;
1058         }
1059 }
1060
1061 int amount_of_chars(char *str)
1062 {
1063         // Since the data is saved as UTF-8 to the cu->str
1064         // The cu->len is not same as the strlen(cu->str)
1065         return strlen(str);
1066 }
1067
1068 static void write_curves(WriteData *wd, ListBase *idbase)
1069 {
1070         Curve *cu;
1071         Nurb *nu;
1072
1073         cu= idbase->first;
1074         while(cu) {
1075                 if(cu->id.us>0 || wd->current) {
1076                         /* write LibData */
1077                         writestruct(wd, ID_CU, "Curve", 1, cu);
1078
1079                         /* direct data */
1080                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
1081                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
1082
1083                         if(cu->vfont) {
1084                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1085                                 writestruct(wd, DATA, "CharInfo", cu->len, cu->strinfo);
1086                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);                           
1087                         }
1088                         else {
1089                                 /* is also the order of reading */
1090                                 nu= cu->nurb.first;
1091                                 while(nu) {
1092                                         writestruct(wd, DATA, "Nurb", 1, nu);
1093                                         nu= nu->next;
1094                                 }
1095                                 nu= cu->nurb.first;
1096                                 while(nu) {
1097                                         if( (nu->type & 7)==CU_BEZIER)
1098                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1099                                         else {
1100                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1101                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1102                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1103                                         }
1104                                         nu= nu->next;
1105                                 }
1106                         }
1107                 }
1108                 cu= cu->id.next;
1109         }
1110
1111         /* flush helps the compression for undo-save */
1112         mywrite(wd, MYWRITE_FLUSH, 0);
1113 }
1114
1115 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1116 {
1117         if (dvlist) {
1118                 int     i;
1119                 
1120                 /* Write the dvert list */
1121                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1122                 
1123                 /* Write deformation data for each dvert */
1124                 for (i=0; i<count; i++) {
1125                         if (dvlist[i].dw)
1126                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1127                 }
1128         }
1129 }
1130
1131 static void write_customdata(WriteData *wd, int count, CustomData *data, int partial_type, int partial_count)
1132 {
1133         int i;
1134
1135         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1136
1137         for (i=0; i<data->totlayer; i++) {
1138                 CustomDataLayer *layer= &data->layers[i];
1139                 char *structname;
1140                 int structnum, datasize;
1141
1142                 if (layer->type == CD_MDEFORMVERT) {
1143                         /* layer types that allocate own memory need special handling */
1144                         write_dverts(wd, count, layer->data);
1145                 }
1146                 else {
1147                         CustomData_file_write_info(layer->type, &structname, &structnum);
1148                         if (structnum) {
1149                                 /* when using partial visibility, the MEdge and MFace layers
1150                                    are smaller than the original, so their type and count is
1151                                    passed to make this work */
1152                                 if (layer->type != partial_type) datasize= structnum*count;
1153                                 else datasize= structnum*partial_count;
1154
1155                                 writestruct(wd, DATA, structname, datasize, layer->data);
1156                         }
1157                         else
1158                                 printf("error: this CustomDataLayer must not be written to file\n");
1159                 }
1160         }
1161 }
1162
1163 static void write_meshs(WriteData *wd, ListBase *idbase)
1164 {
1165         Mesh *mesh;
1166         MultiresLevel *lvl;
1167
1168         mesh= idbase->first;
1169         while(mesh) {
1170                 if(mesh->id.us>0 || wd->current) {
1171                         /* write LibData */
1172 #ifdef WITH_VERSE
1173                         struct VNode *vnode = (VNode*)mesh->vnode;
1174                         if(vnode) {
1175                                 /* mesh has to be created from verse geometry node*/
1176                                 create_meshdata_from_geom_node(mesh, vnode);
1177                                 /* pointer at verse node can't be stored in file */
1178                                 mesh->vnode = NULL;
1179                         }
1180 #endif
1181
1182                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
1183 #ifdef WITH_VERSE
1184                         if(vnode) mesh->vnode = (void*)vnode;
1185 #endif
1186
1187                         /* direct data */
1188                         if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1189
1190                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1191
1192                         if(mesh->pv) {
1193                                 write_customdata(wd, mesh->pv->totvert, &mesh->vdata, -1, 0);
1194                                 write_customdata(wd, mesh->pv->totedge, &mesh->edata,
1195                                         CD_MEDGE, mesh->totedge);
1196                                 write_customdata(wd, mesh->pv->totface, &mesh->fdata,
1197                                         CD_MFACE, mesh->totface);
1198                         }
1199                         else {
1200                                 write_customdata(wd, mesh->totvert, &mesh->vdata, -1, 0);
1201                                 write_customdata(wd, mesh->totedge, &mesh->edata, -1, 0);
1202                                 write_customdata(wd, mesh->totface, &mesh->fdata, -1, 0);
1203                         }
1204
1205                         /* Multires data */
1206                         writestruct(wd, DATA, "Multires", 1, mesh->mr);
1207                         if(mesh->mr) {
1208                                 lvl= mesh->mr->levels.first;
1209                                 if(lvl) {
1210                                         write_customdata(wd, lvl->totvert, &mesh->mr->vdata, -1, 0);
1211                                         write_customdata(wd, lvl->totface, &mesh->mr->fdata, -1, 0);
1212                                         writedata(wd, DATA, sizeof(short)*lvl->totedge, mesh->mr->edge_flags);
1213                                         writedata(wd, DATA, sizeof(char)*lvl->totedge, mesh->mr->edge_creases);
1214                                 }
1215
1216                                 for(; lvl; lvl= lvl->next) {
1217                                         writestruct(wd, DATA, "MultiresLevel", 1, lvl);
1218                                         writestruct(wd, DATA, "MultiresFace", lvl->totface, lvl->faces);
1219                                         writestruct(wd, DATA, "MultiresEdge", lvl->totedge, lvl->edges);
1220                                         writestruct(wd, DATA, "MultiresColFace", lvl->totface, lvl->colfaces);
1221                                 }
1222
1223                                 lvl= mesh->mr->levels.last;
1224                                 if(lvl)
1225                                         writestruct(wd, DATA, "MVert", lvl->totvert, mesh->mr->verts);
1226                         }
1227
1228                         /* PMV data */
1229                         if(mesh->pv) {
1230                                 writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
1231                                 writedata(wd, DATA, sizeof(unsigned int)*mesh->pv->totvert, mesh->pv->vert_map);
1232                                 writedata(wd, DATA, sizeof(int)*mesh->pv->totedge, mesh->pv->edge_map);
1233                                 writestruct(wd, DATA, "MFace", mesh->pv->totface, mesh->pv->old_faces);
1234                                 writestruct(wd, DATA, "MEdge", mesh->pv->totedge, mesh->pv->old_edges);
1235                         }
1236                 }
1237                 mesh= mesh->id.next;
1238         }
1239 }
1240
1241 static void write_lattices(WriteData *wd, ListBase *idbase)
1242 {
1243         Lattice *lt;
1244         
1245         lt= idbase->first;
1246         while(lt) {
1247                 if(lt->id.us>0 || wd->current) {
1248                         /* write LibData */
1249                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1250                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1251
1252                         /* direct data */
1253                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1254                         
1255                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1256                         
1257                 }
1258                 lt= lt->id.next;
1259         }
1260 }
1261
1262 static void write_previews(WriteData *wd, PreviewImage *prv)
1263 {
1264         if (prv) {
1265                 short w = prv->w[1];
1266                 short h = prv->h[1];
1267                 unsigned int *rect = prv->rect[1];
1268                 /* don't write out large previews if not requested */
1269                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1270                         prv->w[1] = 0;
1271                         prv->h[1] = 0;
1272                         prv->rect[1] = NULL;
1273                 }
1274                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1275                 if (prv->rect[0]) writedata(wd, DATA, prv->w[0]*prv->h[0]*sizeof(unsigned int), prv->rect[0]);
1276                 if (prv->rect[1]) writedata(wd, DATA, prv->w[1]*prv->h[1]*sizeof(unsigned int), prv->rect[1]);
1277
1278                 /* restore preview, we still want to keep it in memory even if not saved to file */
1279                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1280                         prv->w[1] = w;
1281                         prv->h[1] = h;
1282                         prv->rect[1] = rect;
1283                 }
1284         }
1285 }
1286
1287 static void write_images(WriteData *wd, ListBase *idbase)
1288 {
1289         Image *ima;
1290         PackedFile * pf;
1291
1292
1293         ima= idbase->first;
1294         while(ima) {
1295                 if(ima->id.us>0 || wd->current) {
1296                         /* write LibData */
1297                         writestruct(wd, ID_IM, "Image", 1, ima);
1298                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1299
1300                         if (ima->packedfile) {
1301                                 pf = ima->packedfile;
1302                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1303                                 writedata(wd, DATA, pf->size, pf->data);
1304                         }
1305
1306                         write_previews(wd, ima->preview);
1307
1308                         }
1309                 ima= ima->id.next;
1310         }
1311         /* flush helps the compression for undo-save */
1312         mywrite(wd, MYWRITE_FLUSH, 0);
1313 }
1314
1315 static void write_textures(WriteData *wd, ListBase *idbase)
1316 {
1317         Tex *tex;
1318
1319         tex= idbase->first;
1320         while(tex) {
1321                 if(tex->id.us>0 || wd->current) {
1322                         /* write LibData */
1323                         writestruct(wd, ID_TE, "Tex", 1, tex);
1324                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1325
1326                         /* direct data */
1327                         if(tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1328                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1329                         if(tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1330                         
1331                         write_previews(wd, tex->preview);
1332                 }
1333                 tex= tex->id.next;
1334         }
1335
1336         /* flush helps the compression for undo-save */
1337         mywrite(wd, MYWRITE_FLUSH, 0);
1338 }
1339
1340 static void write_materials(WriteData *wd, ListBase *idbase)
1341 {
1342         Material *ma;
1343         int a;
1344
1345         ma= idbase->first;
1346         while(ma) {
1347                 if(ma->id.us>0 || wd->current) {
1348                         /* write LibData */
1349                         writestruct(wd, ID_MA, "Material", 1, ma);
1350                         
1351                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1352                           of library blocks that implement this.*/
1353                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1354                           set yet :) */
1355                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1356
1357                         for(a=0; a<MAX_MTEX; a++) {
1358                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1359                         }
1360                         
1361                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1362                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1363                         
1364                         write_scriptlink(wd, &ma->scriptlink);
1365                         
1366                         /* nodetree is integral part of material, no libdata */
1367                         if(ma->nodetree) {
1368                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1369                                 write_nodetree(wd, ma->nodetree);
1370                         }
1371
1372                         write_previews(wd, ma->preview);                        
1373                 }
1374                 ma= ma->id.next;
1375         }
1376 }
1377
1378 static void write_worlds(WriteData *wd, ListBase *idbase)
1379 {
1380         World *wrld;
1381         int a;
1382
1383         wrld= idbase->first;
1384         while(wrld) {
1385                 if(wrld->id.us>0 || wd->current) {
1386                         /* write LibData */
1387                         writestruct(wd, ID_WO, "World", 1, wrld);
1388                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1389
1390                         for(a=0; a<MAX_MTEX; a++) {
1391                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1392                         }
1393
1394                         write_scriptlink(wd, &wrld->scriptlink);
1395
1396                         write_previews(wd, wrld->preview);
1397
1398                 }
1399                 wrld= wrld->id.next;
1400         }
1401 }
1402
1403 static void write_lamps(WriteData *wd, ListBase *idbase)
1404 {
1405         Lamp *la;
1406         int a;
1407
1408         la= idbase->first;
1409         while(la) {
1410                 if(la->id.us>0 || wd->current) {
1411                         /* write LibData */
1412                         writestruct(wd, ID_LA, "Lamp", 1, la);
1413                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1414
1415                         /* direct data */
1416                         for(a=0; a<MAX_MTEX; a++) {
1417                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1418                         }
1419
1420                         if(la->curfalloff)
1421                                 write_curvemapping(wd, la->curfalloff); 
1422                         
1423                         write_scriptlink(wd, &la->scriptlink);
1424
1425                         write_previews(wd, la->preview);
1426
1427                 }
1428                 la= la->id.next;
1429         }
1430 }
1431
1432
1433 static void write_scenes(WriteData *wd, ListBase *scebase)
1434 {
1435         Scene *sce;
1436         Base *base;
1437         Editing *ed;
1438         Sequence *seq;
1439         MetaStack *ms;
1440         Strip *strip;
1441         TimeMarker *marker;
1442         SceneRenderLayer *srl;
1443         int a;
1444         
1445         sce= scebase->first;
1446         while(sce) {
1447                 /* write LibData */
1448                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1449                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1450
1451                 /* direct data */
1452                 base= sce->base.first;
1453                 while(base) {
1454                         writestruct(wd, DATA, "Base", 1, base);
1455                         base= base->next;
1456                 }
1457
1458                 writestruct(wd, DATA, "Radio", 1, sce->radio);
1459                 writestruct(wd, DATA, "ToolSettings", 1, sce->toolsettings);
1460
1461                 for(a=0; a<MAX_MTEX; ++a)
1462                         writestruct(wd, DATA, "MTex", 1, sce->sculptdata.mtex[a]);
1463
1464                 ed= sce->ed;
1465                 if(ed) {
1466                         writestruct(wd, DATA, "Editing", 1, ed);
1467
1468                         /* reset write flags too */
1469                         WHILE_SEQ(&ed->seqbase) {
1470                                 if(seq->strip) seq->strip->done= 0;
1471                                 writestruct(wd, DATA, "Sequence", 1, seq);
1472                         }
1473                         END_SEQ
1474
1475                         WHILE_SEQ(&ed->seqbase) {
1476                                 if(seq->strip && seq->strip->done==0) {
1477                                         /* write strip with 'done' at 0 because readfile */
1478
1479                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1480                                         if(seq->effectdata) {
1481                                                 switch(seq->type){
1482                                                 case SEQ_COLOR:
1483                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
1484                                                         break;
1485                                                 case SEQ_SPEED:
1486                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
1487                                                         break;
1488                                                 case SEQ_WIPE:
1489                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1490                                                         break;
1491                                                 case SEQ_GLOW:
1492                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1493                                                         break;
1494                                                 case SEQ_TRANSFORM:
1495                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
1496                                                         break;
1497                                                 }
1498                                         }
1499
1500                                         strip= seq->strip;
1501                                         writestruct(wd, DATA, "Strip", 1, strip);
1502
1503                                         if(seq->type==SEQ_IMAGE)
1504                                                 writestruct(wd, DATA, "StripElem", strip->len, strip->stripdata);
1505                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
1506                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1507
1508                                         strip->done= 1;
1509                                 }
1510                         }
1511                         END_SEQ
1512                                 
1513                         /* new; meta stack too, even when its nasty restore code */
1514                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1515                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1516                         }
1517                 }
1518
1519                 write_scriptlink(wd, &sce->scriptlink);
1520
1521                 if (sce->r.avicodecdata) {
1522                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1523                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1524                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1525                 }
1526
1527                 if (sce->r.qtcodecdata) {
1528                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1529                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1530                 }
1531
1532                 /* writing dynamic list of TimeMarkers to the blend file */
1533                 for(marker= sce->markers.first; marker; marker= marker->next)
1534                         writestruct(wd, DATA, "TimeMarker", 1, marker);
1535                 
1536                 for(srl= sce->r.layers.first; srl; srl= srl->next)
1537                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
1538                 
1539                 if(sce->nodetree) {
1540                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
1541                         write_nodetree(wd, sce->nodetree);
1542                 }
1543                 
1544                 sce= sce->id.next;
1545         }
1546         /* flush helps the compression for undo-save */
1547         mywrite(wd, MYWRITE_FLUSH, 0);
1548 }
1549
1550 static void write_screens(WriteData *wd, ListBase *scrbase)
1551 {
1552         bScreen *sc;
1553         ScrArea *sa;
1554         ScrVert *sv;
1555         ScrEdge *se;
1556
1557         sc= scrbase->first;
1558         while(sc) {
1559                 /* write LibData */
1560                 writestruct(wd, ID_SCR, "Screen", 1, sc);
1561                 if (sc->id.properties) IDP_WriteProperty(sc->id.properties, wd);
1562
1563                 /* direct data */
1564                 sv= sc->vertbase.first;
1565                 while(sv) {
1566                         writestruct(wd, DATA, "ScrVert", 1, sv);
1567                         sv= sv->next;
1568                 }
1569
1570                 se= sc->edgebase.first;
1571                 while(se) {
1572                         writestruct(wd, DATA, "ScrEdge", 1, se);
1573                         se= se->next;
1574                 }
1575
1576                 sa= sc->areabase.first;
1577                 while(sa) {
1578                         SpaceLink *sl;
1579                         Panel *pa;
1580
1581                         writestruct(wd, DATA, "ScrArea", 1, sa);
1582
1583                         pa= sa->panels.first;
1584                         while(pa) {
1585                                 writestruct(wd, DATA, "Panel", 1, pa);
1586                                 pa= pa->next;
1587                         }
1588
1589                         /* space handler scriptlinks */
1590                         write_scriptlink(wd, &sa->scriptlink);
1591
1592                         sl= sa->spacedata.first;
1593                         while(sl) {
1594                                 if(sl->spacetype==SPACE_VIEW3D) {
1595                                         View3D *v3d= (View3D*) sl;
1596                                         writestruct(wd, DATA, "View3D", 1, v3d);
1597                                         if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
1598                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
1599                                         if(v3d->clipbb) writestruct(wd, DATA, "BoundBox", 1, v3d->clipbb);
1600                                 }
1601                                 else if(sl->spacetype==SPACE_IPO) {
1602                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
1603                                 }
1604                                 else if(sl->spacetype==SPACE_BUTS) {
1605                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
1606                                 }
1607                                 else if(sl->spacetype==SPACE_FILE) {
1608                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
1609                                 }
1610                                 else if(sl->spacetype==SPACE_SEQ) {
1611                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
1612                                 }
1613                                 else if(sl->spacetype==SPACE_OOPS) {
1614                                         SpaceOops *so= (SpaceOops *)sl;
1615                                         Oops *oops;
1616
1617                                         /* cleanup */
1618                                         oops= so->oops.first;
1619                                         while(oops) {
1620                                                 Oops *oopsn= oops->next;
1621                                                 if(oops->id==0) {
1622                                                         BLI_remlink(&so->oops, oops);
1623                                                         free_oops(oops);
1624                                                 }
1625                                                 oops= oopsn;
1626                                         }
1627
1628                                         /* ater cleanup, because of listbase! */
1629                                         writestruct(wd, DATA, "SpaceOops", 1, so);
1630
1631                                         oops= so->oops.first;
1632                                         while(oops) {
1633                                                 writestruct(wd, DATA, "Oops", 1, oops);
1634                                                 oops= oops->next;
1635                                         }
1636                                         /* outliner */
1637                                         if(so->treestore) {
1638                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
1639                                                 if(so->treestore->data)
1640                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
1641                                         }
1642                                 }
1643                                 else if(sl->spacetype==SPACE_IMAGE) {
1644                                         SpaceImage *sima= (SpaceImage *)sl;
1645                                         
1646                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
1647                                         if(sima->cumap)
1648                                                 write_curvemapping(wd, sima->cumap);                                    
1649                                 }
1650                                 else if(sl->spacetype==SPACE_IMASEL) {
1651                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
1652                                 }
1653                                 else if(sl->spacetype==SPACE_TEXT) {
1654                                         writestruct(wd, DATA, "SpaceText", 1, sl);
1655                                 }
1656                                 else if(sl->spacetype==SPACE_SCRIPT) {
1657                                         SpaceScript *sc = (SpaceScript*)sl;
1658                                         sc->but_refs = NULL;
1659                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
1660                                 }
1661                                 else if(sl->spacetype==SPACE_ACTION) {
1662                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
1663                                 }
1664                                 else if(sl->spacetype==SPACE_SOUND) {
1665                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
1666                                 }
1667                                 else if(sl->spacetype==SPACE_NLA){
1668                                         writestruct(wd, DATA, "SpaceNla", 1, sl);
1669                                 }
1670                                 else if(sl->spacetype==SPACE_TIME){
1671                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
1672                                 }
1673                                 else if(sl->spacetype==SPACE_NODE){
1674                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
1675                                 }
1676                                 sl= sl->next;
1677                         }
1678
1679                         sa= sa->next;
1680                 }
1681
1682                 sc= sc->id.next;
1683         }
1684 }
1685
1686 static void write_libraries(WriteData *wd, Main *main)
1687 {
1688         ListBase *lbarray[30];
1689         ID *id;
1690         int a, tot, foundone;
1691
1692         for(; main; main= main->next) {
1693
1694                 a=tot= set_listbasepointers(main, lbarray);
1695
1696                 /* test: is lib being used */
1697                 foundone= 0;
1698                 while(tot--) {
1699                         for(id= lbarray[tot]->first; id; id= id->next) {
1700                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
1701                                         foundone= 1;
1702                                         break;
1703                                 }
1704                         }
1705                         if(foundone) break;
1706                 }
1707
1708                 if(foundone) {
1709                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
1710
1711                         while(a--) {
1712                                 for(id= lbarray[a]->first; id; id= id->next) {
1713                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
1714                                                 writestruct(wd, ID_ID, "ID", 1, id);
1715                                         }
1716                                 }
1717                         }
1718                 }
1719         }
1720 }
1721
1722 static void write_bone(WriteData *wd, Bone* bone)
1723 {
1724         Bone*   cbone;
1725
1726         // PATCH for upward compatibility after 2.37+ armature recode
1727         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
1728                 
1729         // Write this bone
1730         writestruct(wd, DATA, "Bone", 1, bone);
1731         
1732         // Write Children
1733         cbone= bone->childbase.first;
1734         while(cbone) {
1735                 write_bone(wd, cbone);
1736                 cbone= cbone->next;
1737         }
1738 }
1739
1740 static void write_armatures(WriteData *wd, ListBase *idbase)
1741 {
1742         bArmature       *arm;
1743         Bone            *bone;
1744
1745         arm=idbase->first;
1746         while (arm) {
1747                 if (arm->id.us>0 || wd->current) {
1748                         writestruct(wd, ID_AR, "bArmature", 1, arm);
1749                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
1750
1751                         /* Direct data */
1752                         bone= arm->bonebase.first;
1753                         while(bone) {
1754                                 write_bone(wd, bone);
1755                                 bone=bone->next;
1756                         }
1757                 }
1758                 arm=arm->id.next;
1759         }
1760
1761         /* flush helps the compression for undo-save */
1762         mywrite(wd, MYWRITE_FLUSH, 0);
1763 }
1764
1765 static void write_actions(WriteData *wd, ListBase *idbase)
1766 {
1767         bAction                 *act;
1768         bActionChannel  *chan;
1769         
1770         for(act=idbase->first; act; act= act->id.next) {
1771                 if (act->id.us>0 || wd->current) {
1772                         writestruct(wd, ID_AC, "bAction", 1, act);
1773                         if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
1774
1775                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1776                                 writestruct(wd, DATA, "bActionChannel", 1, chan);
1777                                 write_constraint_channels(wd, &chan->constraintChannels);
1778                         }
1779                 }
1780         }
1781 }
1782
1783 static void write_texts(WriteData *wd, ListBase *idbase)
1784 {
1785         Text *text;
1786         TextLine *tmp;
1787
1788         text= idbase->first;
1789         while(text) {
1790                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
1791
1792                 /* write LibData */
1793                 writestruct(wd, ID_TXT, "Text", 1, text);
1794                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
1795                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
1796
1797                 if(!(text->flags & TXT_ISEXT)) {
1798                         /* now write the text data, in two steps for optimization in the readfunction */
1799                         tmp= text->lines.first;
1800                         while (tmp) {
1801                                 writestruct(wd, DATA, "TextLine", 1, tmp);
1802                                 tmp= tmp->next;
1803                         }
1804
1805                         tmp= text->lines.first;
1806                         while (tmp) {
1807                                 writedata(wd, DATA, tmp->len+1, tmp->line);
1808                                 tmp= tmp->next;
1809                         }
1810                 }
1811                 text= text->id.next;
1812         }
1813
1814         /* flush helps the compression for undo-save */
1815         mywrite(wd, MYWRITE_FLUSH, 0);
1816 }
1817
1818 static void write_sounds(WriteData *wd, ListBase *idbase)
1819 {
1820         bSound *sound;
1821         bSample *sample;
1822
1823         PackedFile * pf;
1824
1825         // set all samples to unsaved status
1826
1827         sample = samples->first;
1828         while (sample) {
1829                 sample->flags |= SAMPLE_NEEDS_SAVE;
1830                 sample = sample->id.next;
1831         }
1832
1833         sound= idbase->first;
1834         while(sound) {
1835                 if(sound->id.us>0 || wd->current) {
1836                         // do we need to save the packedfile as well ?
1837                         sample = sound->sample;
1838                         if (sample) {
1839                                 if (sample->flags & SAMPLE_NEEDS_SAVE) {
1840                                         sound->newpackedfile = sample->packedfile;
1841                                         sample->flags &= ~SAMPLE_NEEDS_SAVE;
1842                                 } else {
1843                                         sound->newpackedfile = NULL;
1844                                 }
1845                         }
1846
1847                         /* write LibData */
1848                         writestruct(wd, ID_SO, "bSound", 1, sound);
1849                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
1850
1851                         if (sound->newpackedfile) {
1852                                 pf = sound->newpackedfile;
1853                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1854                                 writedata(wd, DATA, pf->size, pf->data);
1855                         }
1856
1857                         if (sample) {
1858                                 sound->newpackedfile = sample->packedfile;
1859                         }
1860                 }
1861                 sound= sound->id.next;
1862         }
1863
1864         /* flush helps the compression for undo-save */
1865         mywrite(wd, MYWRITE_FLUSH, 0);
1866 }
1867
1868 static void write_groups(WriteData *wd, ListBase *idbase)
1869 {
1870         Group *group;
1871         GroupObject *go;
1872
1873         for(group= idbase->first; group; group= group->id.next) {
1874                 if(group->id.us>0 || wd->current) {
1875                         /* write LibData */
1876                         writestruct(wd, ID_GR, "Group", 1, group);
1877                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
1878
1879                         go= group->gobject.first;
1880                         while(go) {
1881                                 writestruct(wd, DATA, "GroupObject", 1, go);
1882                                 go= go->next;
1883                         }
1884                 }
1885         }
1886 }
1887
1888 static void write_nodetrees(WriteData *wd, ListBase *idbase)
1889 {
1890         bNodeTree *ntree;
1891         
1892         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
1893                 if (ntree->id.us>0 || wd->current) {
1894                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
1895                         write_nodetree(wd, ntree);
1896                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
1897                 }
1898         }
1899 }
1900
1901 static void write_brushes(WriteData *wd, ListBase *idbase)
1902 {
1903         Brush *brush;
1904         int a;
1905         
1906         for(brush=idbase->first; brush; brush= brush->id.next) {
1907                 if(brush->id.us>0 || wd->current) {
1908                         writestruct(wd, ID_BR, "Brush", 1, brush);
1909                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
1910                         for(a=0; a<MAX_MTEX; a++)
1911                                 if(brush->mtex[a])
1912                                         writestruct(wd, DATA, "MTex", 1, brush->mtex[a]);
1913                 }
1914         }
1915 }
1916
1917 static void write_global(WriteData *wd)
1918 {
1919         FileGlobal fg;
1920         char subvstr[8];
1921         
1922         fg.curscreen= G.curscreen;
1923         fg.curscene= G.scene;
1924         fg.displaymode= G.displaymode;
1925         fg.winpos= G.winpos;
1926         fg.fileflags= (G.fileflags & ~G_FILE_NO_UI);    // prevent to save this, is not good convention, and feature with concerns...
1927         fg.globalf= G.f;
1928
1929         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
1930         memcpy(fg.subvstr, subvstr, 4);
1931         
1932         fg.subversion= BLENDER_SUBVERSION;
1933         fg.minversion= BLENDER_MINVERSION;
1934         fg.minsubversion= BLENDER_MINSUBVERSION;
1935         
1936         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
1937 }
1938
1939 /* if MemFile * there's filesave to memory */
1940 static int write_file_handle(int handle, MemFile *compare, MemFile *current, int write_user_block, int write_flags)
1941 {
1942         BHead bhead;
1943         ListBase mainlist;
1944         char buf[16];
1945         WriteData *wd;
1946
1947         blo_split_main(&mainlist, G.main);
1948
1949         wd= bgnwrite(handle, compare, current, write_flags);
1950         
1951         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (G.order==B_ENDIAN)?'V':'v', G.version);
1952         mywrite(wd, buf, 12);
1953
1954         write_renderinfo(wd);
1955         write_global(wd);
1956
1957         if(current==NULL)
1958                 write_screens  (wd, &G.main->screen);   /* no UI save in undo */
1959         write_scenes   (wd, &G.main->scene);
1960         write_curves   (wd, &G.main->curve);
1961         write_mballs   (wd, &G.main->mball);
1962         write_images   (wd, &G.main->image);
1963         write_cameras  (wd, &G.main->camera);
1964         write_lamps    (wd, &G.main->lamp);
1965         write_lattices (wd, &G.main->latt);
1966         write_vfonts   (wd, &G.main->vfont);
1967         write_ipos     (wd, &G.main->ipo);
1968         write_keys     (wd, &G.main->key);
1969         write_worlds   (wd, &G.main->world);
1970         write_texts    (wd, &G.main->text);
1971         write_sounds   (wd, &G.main->sound);
1972         write_groups   (wd, &G.main->group);
1973         write_armatures(wd, &G.main->armature);
1974         write_actions  (wd, &G.main->action);
1975         write_objects  (wd, &G.main->object);
1976         write_materials(wd, &G.main->mat);
1977         write_textures (wd, &G.main->tex);
1978         write_meshs    (wd, &G.main->mesh);
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__ */