== PoseLib - Overhauled Implementation ==
[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->child) writestruct(wd, DATA, "ChildParticle", psys->totchild ,psys->child);
563                 writestruct(wd, DATA, "SoftBody", 1, psys->soft);
564         }
565 }
566
567 static void write_properties(WriteData *wd, ListBase *lb)
568 {
569         bProperty *prop;
570
571         prop= lb->first;
572         while(prop) {
573                 writestruct(wd, DATA, "bProperty", 1, prop);
574
575                 if(prop->poin && prop->poin != &prop->data)
576                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
577
578                 prop= prop->next;
579         }
580 }
581
582 static void write_sensors(WriteData *wd, ListBase *lb)
583 {
584         bSensor *sens;
585
586         sens= lb->first;
587         while(sens) {
588                 writestruct(wd, DATA, "bSensor", 1, sens);
589
590                 writedata(wd, DATA, sizeof(void *)*sens->totlinks, sens->links);
591
592                 switch(sens->type) {
593                 case SENS_NEAR:
594                         writestruct(wd, DATA, "bNearSensor", 1, sens->data);
595                         break;
596                 case SENS_MOUSE:
597                         writestruct(wd, DATA, "bMouseSensor", 1, sens->data);
598                         break;
599                 case SENS_TOUCH:
600                         writestruct(wd, DATA, "bTouchSensor", 1, sens->data);
601                         break;
602                 case SENS_KEYBOARD:
603                         writestruct(wd, DATA, "bKeyboardSensor", 1, sens->data);
604                         break;
605                 case SENS_PROPERTY:
606                         writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
607                         break;
608                 case SENS_COLLISION:
609                         writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
610                         break;
611                 case SENS_RADAR:
612                         writestruct(wd, DATA, "bRadarSensor", 1, sens->data);
613                         break;
614                 case SENS_RANDOM:
615                         writestruct(wd, DATA, "bRandomSensor", 1, sens->data);
616                         break;
617                 case SENS_RAY:
618                         writestruct(wd, DATA, "bRaySensor", 1, sens->data);
619                         break;
620                 case SENS_MESSAGE:
621                         writestruct(wd, DATA, "bMessageSensor", 1, sens->data);
622                         break;
623                 case SENS_JOYSTICK:
624                         writestruct(wd, DATA, "bJoystickSensor", 1, sens->data);
625                         break;
626                 default:
627                         ; /* error: don't know how to write this file */
628                 }
629
630                 sens= sens->next;
631         }
632 }
633
634 static void write_controllers(WriteData *wd, ListBase *lb)
635 {
636         bController *cont;
637
638         cont= lb->first;
639         while(cont) {
640                 writestruct(wd, DATA, "bController", 1, cont);
641
642                 writedata(wd, DATA, sizeof(void *)*cont->totlinks, cont->links);
643
644                 switch(cont->type) {
645                 case CONT_EXPRESSION:
646                         writestruct(wd, DATA, "bExpressionCont", 1, cont->data);
647                         break;
648                 case CONT_PYTHON:
649                         writestruct(wd, DATA, "bPythonCont", 1, cont->data);
650                         break;
651                 default:
652                         ; /* error: don't know how to write this file */
653                 }
654
655                 cont= cont->next;
656         }
657 }
658
659 static void write_actuators(WriteData *wd, ListBase *lb)
660 {
661         bActuator *act;
662
663         act= lb->first;
664         while(act) {
665                 writestruct(wd, DATA, "bActuator", 1, act);
666
667                 switch(act->type) {
668                 case ACT_ACTION:
669                         writestruct(wd, DATA, "bActionActuator", 1, act->data);
670                         break;
671                 case ACT_SOUND:
672                         writestruct(wd, DATA, "bSoundActuator", 1, act->data);
673                         break;
674                 case ACT_CD:
675                         writestruct(wd, DATA, "bCDActuator", 1, act->data);
676                         break;
677                 case ACT_OBJECT:
678                         writestruct(wd, DATA, "bObjectActuator", 1, act->data);
679                         break;
680                 case ACT_IPO:
681                         writestruct(wd, DATA, "bIpoActuator", 1, act->data);
682                         break;
683                 case ACT_PROPERTY:
684                         writestruct(wd, DATA, "bPropertyActuator", 1, act->data);
685                         break;
686                 case ACT_CAMERA:
687                         writestruct(wd, DATA, "bCameraActuator", 1, act->data);
688                         break;
689                 case ACT_CONSTRAINT:
690                         writestruct(wd, DATA, "bConstraintActuator", 1, act->data);
691                         break;
692                 case ACT_EDIT_OBJECT:
693                         writestruct(wd, DATA, "bEditObjectActuator", 1, act->data);
694                         break;
695                 case ACT_SCENE:
696                         writestruct(wd, DATA, "bSceneActuator", 1, act->data);
697                         break;
698                 case ACT_GROUP:
699                         writestruct(wd, DATA, "bGroupActuator", 1, act->data);
700                         break;
701                 case ACT_RANDOM:
702                         writestruct(wd, DATA, "bRandomActuator", 1, act->data);
703                         break;
704                 case ACT_MESSAGE:
705                         writestruct(wd, DATA, "bMessageActuator", 1, act->data);
706                         break;
707                 case ACT_GAME:
708                         writestruct(wd, DATA, "bGameActuator", 1, act->data);
709                         break;
710                 case ACT_VISIBILITY:
711                         writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
712                         break;
713                 default:
714                         ; /* error: don't know how to write this file */
715                 }
716
717                 act= act->next;
718         }
719 }
720
721 static void write_nlastrips(WriteData *wd, ListBase *nlabase)
722 {
723         bActionStrip *strip;
724         bActionModifier *amod;
725         
726         for (strip=nlabase->first; strip; strip=strip->next)
727                 writestruct(wd, DATA, "bActionStrip", 1, strip);
728         for (strip=nlabase->first; strip; strip=strip->next) {
729                 for(amod= strip->modifiers.first; amod; amod= amod->next)
730                         writestruct(wd, DATA, "bActionModifier", 1, amod);
731         }
732 }
733
734 static void write_constraints(WriteData *wd, ListBase *conlist)
735 {
736         bConstraint *con;
737
738         for (con=conlist->first; con; con=con->next) {
739                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
740                 
741                 /* Write the specific data */
742                 if (cti && con->data) {
743                         /* firstly, just write the plain con->data struct */
744                         writestruct(wd, DATA, cti->structName, 1, con->data);
745                         
746                         /* do any constraint specific stuff */
747                         switch (con->type) {
748                                 case CONSTRAINT_TYPE_PYTHON:
749                                 {
750                                         bPythonConstraint *data = (bPythonConstraint *)con->data;
751                                         bConstraintTarget *ct;
752                                         
753                                         /* write targets */
754                                         for (ct= data->targets.first; ct; ct= ct->next)
755                                                 writestruct(wd, DATA, "bConstraintTarget", 1, ct);
756                                         
757                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
758                                          of library blocks that implement this.*/
759                                         IDP_WriteProperty(data->prop, wd);
760                                 }
761                                 break;
762                         }
763                 }
764                 
765                 /* Write the constraint */
766                 writestruct(wd, DATA, "bConstraint", 1, con);
767         }
768 }
769
770 static void write_pose(WriteData *wd, bPose *pose)
771 {
772         bPoseChannel *chan;
773
774         /* Write each channel */
775         if (!pose)
776                 return;
777
778         /* Write channels */
779         for (chan=pose->chanbase.first; chan; chan=chan->next) {
780                 write_constraints(wd, &chan->constraints);
781                 
782                 /* prevent crashes with autosave, when a bone duplicated in editmode has not yet been assigned to its posechannel */
783                 if (chan->bone) 
784                         chan->selectflag= chan->bone->flag & (BONE_SELECTED|BONE_ACTIVE); /* gets restored on read, for library armatures */
785                 
786                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
787         }
788
789         /* Write this pose */
790         writestruct(wd, DATA, "bPose", 1, pose);
791 }
792
793 static void write_defgroups(WriteData *wd, ListBase *defbase)
794 {
795         bDeformGroup    *defgroup;
796
797         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
798                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
799 }
800
801 static void write_constraint_channels(WriteData *wd, ListBase *chanbase)
802 {
803         bConstraintChannel *chan;
804
805         for (chan = chanbase->first; chan; chan=chan->next)
806                 writestruct(wd, DATA, "bConstraintChannel", 1, chan);
807
808 }
809
810 static void write_modifiers(WriteData *wd, ListBase *modbase)
811 {
812         ModifierData *md;
813
814         if (modbase == NULL) return;
815         for (md=modbase->first; md; md= md->next) {
816                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
817                 if (mti == NULL) return;
818                 
819                 writestruct(wd, DATA, mti->structName, 1, md);
820                         
821                 if (md->type==eModifierType_Hook) {
822                         HookModifierData *hmd = (HookModifierData*) md;
823                         
824                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
825                 }
826                 else if (md->type==eModifierType_MeshDeform) {
827                         MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
828                         int size = mmd->dyngridsize;
829
830                         writedata(wd, DATA, sizeof(float)*mmd->totvert*mmd->totcagevert,
831                                 mmd->bindweights);
832                         writedata(wd, DATA, sizeof(float)*3*mmd->totcagevert,
833                                 mmd->bindcos);
834                         writestruct(wd, DATA, "MDefCell", size*size*size, mmd->dyngrid);
835                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->dyninfluences);
836                         writedata(wd, DATA, sizeof(int)*mmd->totvert, mmd->dynverts);
837                 }
838         }
839 }
840
841 static void write_objects(WriteData *wd, ListBase *idbase)
842 {
843         Object *ob;
844         
845         ob= idbase->first;
846         while(ob) {
847                 if(ob->id.us>0 || wd->current) {
848                         /* write LibData */
849 #ifdef WITH_VERSE
850                         /* pointer at vnode stored in file have to be NULL */
851                         struct VNode *vnode = (VNode*)ob->vnode;
852                         if(vnode) ob->vnode = NULL;
853 #endif
854                         writestruct(wd, ID_OB, "Object", 1, ob);
855 #ifdef WITH_VERSE
856                         if(vnode) ob->vnode = (void*)vnode;
857 #endif
858
859                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
860                           of library blocks that implement this.*/
861                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
862
863                         /* direct data */
864                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
865                         write_effects(wd, &ob->effect);
866                         write_properties(wd, &ob->prop);
867                         write_sensors(wd, &ob->sensors);
868                         write_controllers(wd, &ob->controllers);
869                         write_actuators(wd, &ob->actuators);
870                         write_scriptlink(wd, &ob->scriptlink);
871                         write_pose(wd, ob->pose);
872                         write_defgroups(wd, &ob->defbase);
873                         write_constraints(wd, &ob->constraints);
874                         write_constraint_channels(wd, &ob->constraintChannels);
875                         write_nlastrips(wd, &ob->nlastrips);
876                         
877                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
878                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
879                         writestruct(wd, DATA, "FluidsimSettings", 1, ob->fluidsimSettings); // NT
880                         
881                         write_particlesystems(wd, &ob->particlesystem);
882                         write_modifiers(wd, &ob->modifiers);
883                 }
884                 ob= ob->id.next;
885         }
886
887         /* flush helps the compression for undo-save */
888         mywrite(wd, MYWRITE_FLUSH, 0);
889 }
890
891
892 static void write_vfonts(WriteData *wd, ListBase *idbase)
893 {
894         VFont *vf;
895         PackedFile * pf;
896
897         vf= idbase->first;
898         while(vf) {
899                 if(vf->id.us>0 || wd->current) {
900                         /* write LibData */
901                         writestruct(wd, ID_VF, "VFont", 1, vf);
902                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
903
904                         /* direct data */
905
906                         if (vf->packedfile) {
907                                 pf = vf->packedfile;
908                                 writestruct(wd, DATA, "PackedFile", 1, pf);
909                                 writedata(wd, DATA, pf->size, pf->data);
910                         }
911                 }
912
913                 vf= vf->id.next;
914         }
915 }
916
917 static void write_ipos(WriteData *wd, ListBase *idbase)
918 {
919         Ipo *ipo;
920         IpoCurve *icu;
921
922         ipo= idbase->first;
923         while(ipo) {
924                 if(ipo->id.us>0 || wd->current) {
925                         /* write LibData */
926                         writestruct(wd, ID_IP, "Ipo", 1, ipo);
927                         if (ipo->id.properties) IDP_WriteProperty(ipo->id.properties, wd);
928
929                         /* direct data */
930                         icu= ipo->curve.first;
931                         while(icu) {
932                                 writestruct(wd, DATA, "IpoCurve", 1, icu);
933                                 icu= icu->next;
934                         }
935
936                         icu= ipo->curve.first;
937                         while(icu) {
938                                 if(icu->bezt)  writestruct(wd, DATA, "BezTriple", icu->totvert, icu->bezt);
939                                 if(icu->bp)  writestruct(wd, DATA, "BPoint", icu->totvert, icu->bp);
940                                 if(icu->driver)  writestruct(wd, DATA, "IpoDriver", 1, icu->driver);
941                                 icu= icu->next;
942                         }
943                 }
944
945                 ipo= ipo->id.next;
946         }
947
948         /* flush helps the compression for undo-save */
949         mywrite(wd, MYWRITE_FLUSH, 0);
950 }
951
952 static void write_keys(WriteData *wd, ListBase *idbase)
953 {
954         Key *key;
955         KeyBlock *kb;
956
957         key= idbase->first;
958         while(key) {
959                 if(key->id.us>0 || wd->current) {
960                         /* write LibData */
961                         writestruct(wd, ID_KE, "Key", 1, key);
962                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
963
964                         /* direct data */
965                         kb= key->block.first;
966                         while(kb) {
967                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
968                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
969                                 kb= kb->next;
970                         }
971                 }
972
973                 key= key->id.next;
974         }
975         /* flush helps the compression for undo-save */
976         mywrite(wd, MYWRITE_FLUSH, 0);
977 }
978
979 static void write_cameras(WriteData *wd, ListBase *idbase)
980 {
981         Camera *cam;
982
983         cam= idbase->first;
984         while(cam) {
985                 if(cam->id.us>0 || wd->current) {
986                         /* write LibData */
987                         writestruct(wd, ID_CA, "Camera", 1, cam);
988                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
989
990                         /* direct data */
991                         write_scriptlink(wd, &cam->scriptlink);
992                 }
993
994                 cam= cam->id.next;
995         }
996 }
997
998 static void write_mballs(WriteData *wd, ListBase *idbase)
999 {
1000         MetaBall *mb;
1001         MetaElem *ml;
1002
1003         mb= idbase->first;
1004         while(mb) {
1005                 if(mb->id.us>0 || wd->current) {
1006                         /* write LibData */
1007                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
1008                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
1009
1010                         /* direct data */
1011                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
1012
1013                         ml= mb->elems.first;
1014                         while(ml) {
1015                                 writestruct(wd, DATA, "MetaElem", 1, ml);
1016                                 ml= ml->next;
1017                         }
1018                 }
1019                 mb= mb->id.next;
1020         }
1021 }
1022
1023 int amount_of_chars(char *str)
1024 {
1025         // Since the data is saved as UTF-8 to the cu->str
1026         // The cu->len is not same as the strlen(cu->str)
1027         return strlen(str);
1028 }
1029
1030 static void write_curves(WriteData *wd, ListBase *idbase)
1031 {
1032         Curve *cu;
1033         Nurb *nu;
1034
1035         cu= idbase->first;
1036         while(cu) {
1037                 if(cu->id.us>0 || wd->current) {
1038                         /* write LibData */
1039                         writestruct(wd, ID_CU, "Curve", 1, cu);
1040
1041                         /* direct data */
1042                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
1043                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
1044
1045                         if(cu->vfont) {
1046                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1047                                 writestruct(wd, DATA, "CharInfo", cu->len, cu->strinfo);
1048                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);                           
1049                         }
1050                         else {
1051                                 /* is also the order of reading */
1052                                 nu= cu->nurb.first;
1053                                 while(nu) {
1054                                         writestruct(wd, DATA, "Nurb", 1, nu);
1055                                         nu= nu->next;
1056                                 }
1057                                 nu= cu->nurb.first;
1058                                 while(nu) {
1059                                         if( (nu->type & 7)==CU_BEZIER)
1060                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1061                                         else {
1062                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1063                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1064                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1065                                         }
1066                                         nu= nu->next;
1067                                 }
1068                         }
1069                 }
1070                 cu= cu->id.next;
1071         }
1072
1073         /* flush helps the compression for undo-save */
1074         mywrite(wd, MYWRITE_FLUSH, 0);
1075 }
1076
1077 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1078 {
1079         if (dvlist) {
1080                 int     i;
1081                 
1082                 /* Write the dvert list */
1083                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1084                 
1085                 /* Write deformation data for each dvert */
1086                 for (i=0; i<count; i++) {
1087                         if (dvlist[i].dw)
1088                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1089                 }
1090         }
1091 }
1092
1093 static void write_customdata(WriteData *wd, int count, CustomData *data, int partial_type, int partial_count)
1094 {
1095         int i;
1096
1097         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1098
1099         for (i=0; i<data->totlayer; i++) {
1100                 CustomDataLayer *layer= &data->layers[i];
1101                 char *structname;
1102                 int structnum, datasize;
1103
1104                 if (layer->type == CD_MDEFORMVERT) {
1105                         /* layer types that allocate own memory need special handling */
1106                         write_dverts(wd, count, layer->data);
1107                 }
1108                 else {
1109                         CustomData_file_write_info(layer->type, &structname, &structnum);
1110                         if (structnum) {
1111                                 /* when using partial visibility, the MEdge and MFace layers
1112                                    are smaller than the original, so their type and count is
1113                                    passed to make this work */
1114                                 if (layer->type != partial_type) datasize= structnum*count;
1115                                 else datasize= structnum*partial_count;
1116
1117                                 writestruct(wd, DATA, structname, datasize, layer->data);
1118                         }
1119                         else
1120                                 printf("error: this CustomDataLayer must not be written to file\n");
1121                 }
1122         }
1123 }
1124
1125 static void write_meshs(WriteData *wd, ListBase *idbase)
1126 {
1127         Mesh *mesh;
1128         MultiresLevel *lvl;
1129
1130         mesh= idbase->first;
1131         while(mesh) {
1132                 if(mesh->id.us>0 || wd->current) {
1133                         /* write LibData */
1134 #ifdef WITH_VERSE
1135                         struct VNode *vnode = (VNode*)mesh->vnode;
1136                         if(vnode) {
1137                                 /* mesh has to be created from verse geometry node*/
1138                                 create_meshdata_from_geom_node(mesh, vnode);
1139                                 /* pointer at verse node can't be stored in file */
1140                                 mesh->vnode = NULL;
1141                         }
1142 #endif
1143
1144                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
1145 #ifdef WITH_VERSE
1146                         if(vnode) mesh->vnode = (void*)vnode;
1147 #endif
1148
1149                         /* direct data */
1150                         if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1151
1152                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1153
1154                         if(mesh->pv) {
1155                                 write_customdata(wd, mesh->pv->totvert, &mesh->vdata, -1, 0);
1156                                 write_customdata(wd, mesh->pv->totedge, &mesh->edata,
1157                                         CD_MEDGE, mesh->totedge);
1158                                 write_customdata(wd, mesh->pv->totface, &mesh->fdata,
1159                                         CD_MFACE, mesh->totface);
1160                         }
1161                         else {
1162                                 write_customdata(wd, mesh->totvert, &mesh->vdata, -1, 0);
1163                                 write_customdata(wd, mesh->totedge, &mesh->edata, -1, 0);
1164                                 write_customdata(wd, mesh->totface, &mesh->fdata, -1, 0);
1165                         }
1166
1167                         /* Multires data */
1168                         writestruct(wd, DATA, "Multires", 1, mesh->mr);
1169                         if(mesh->mr) {
1170                                 lvl= mesh->mr->levels.first;
1171                                 if(lvl) {
1172                                         write_customdata(wd, lvl->totvert, &mesh->mr->vdata, -1, 0);
1173                                         write_customdata(wd, lvl->totface, &mesh->mr->fdata, -1, 0);
1174                                         writedata(wd, DATA, sizeof(short)*lvl->totedge, mesh->mr->edge_flags);
1175                                         writedata(wd, DATA, sizeof(char)*lvl->totedge, mesh->mr->edge_creases);
1176                                 }
1177
1178                                 for(; lvl; lvl= lvl->next) {
1179                                         writestruct(wd, DATA, "MultiresLevel", 1, lvl);
1180                                         writestruct(wd, DATA, "MultiresFace", lvl->totface, lvl->faces);
1181                                         writestruct(wd, DATA, "MultiresEdge", lvl->totedge, lvl->edges);
1182                                         writestruct(wd, DATA, "MultiresColFace", lvl->totface, lvl->colfaces);
1183                                 }
1184
1185                                 lvl= mesh->mr->levels.last;
1186                                 if(lvl)
1187                                         writestruct(wd, DATA, "MVert", lvl->totvert, mesh->mr->verts);
1188                         }
1189
1190                         /* PMV data */
1191                         if(mesh->pv) {
1192                                 writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
1193                                 writedata(wd, DATA, sizeof(unsigned int)*mesh->pv->totvert, mesh->pv->vert_map);
1194                                 writedata(wd, DATA, sizeof(int)*mesh->pv->totedge, mesh->pv->edge_map);
1195                                 writestruct(wd, DATA, "MFace", mesh->pv->totface, mesh->pv->old_faces);
1196                                 writestruct(wd, DATA, "MEdge", mesh->pv->totedge, mesh->pv->old_edges);
1197                         }
1198                 }
1199                 mesh= mesh->id.next;
1200         }
1201 }
1202
1203 static void write_lattices(WriteData *wd, ListBase *idbase)
1204 {
1205         Lattice *lt;
1206         
1207         lt= idbase->first;
1208         while(lt) {
1209                 if(lt->id.us>0 || wd->current) {
1210                         /* write LibData */
1211                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1212                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1213
1214                         /* direct data */
1215                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1216                         
1217                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1218                         
1219                 }
1220                 lt= lt->id.next;
1221         }
1222 }
1223
1224 static void write_previews(WriteData *wd, PreviewImage *prv)
1225 {
1226         if (prv) {
1227                 short w = prv->w[1];
1228                 short h = prv->h[1];
1229                 unsigned int *rect = prv->rect[1];
1230                 /* don't write out large previews if not requested */
1231                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1232                         prv->w[1] = 0;
1233                         prv->h[1] = 0;
1234                         prv->rect[1] = NULL;
1235                 }
1236                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1237                 if (prv->rect[0]) writedata(wd, DATA, prv->w[0]*prv->h[0]*sizeof(unsigned int), prv->rect[0]);
1238                 if (prv->rect[1]) writedata(wd, DATA, prv->w[1]*prv->h[1]*sizeof(unsigned int), prv->rect[1]);
1239
1240                 /* restore preview, we still want to keep it in memory even if not saved to file */
1241                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1242                         prv->w[1] = w;
1243                         prv->h[1] = h;
1244                         prv->rect[1] = rect;
1245                 }
1246         }
1247 }
1248
1249 static void write_images(WriteData *wd, ListBase *idbase)
1250 {
1251         Image *ima;
1252         PackedFile * pf;
1253
1254
1255         ima= idbase->first;
1256         while(ima) {
1257                 if(ima->id.us>0 || wd->current) {
1258                         /* write LibData */
1259                         writestruct(wd, ID_IM, "Image", 1, ima);
1260                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1261
1262                         if (ima->packedfile) {
1263                                 pf = ima->packedfile;
1264                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1265                                 writedata(wd, DATA, pf->size, pf->data);
1266                         }
1267
1268                         write_previews(wd, ima->preview);
1269
1270                         }
1271                 ima= ima->id.next;
1272         }
1273         /* flush helps the compression for undo-save */
1274         mywrite(wd, MYWRITE_FLUSH, 0);
1275 }
1276
1277 static void write_textures(WriteData *wd, ListBase *idbase)
1278 {
1279         Tex *tex;
1280
1281         tex= idbase->first;
1282         while(tex) {
1283                 if(tex->id.us>0 || wd->current) {
1284                         /* write LibData */
1285                         writestruct(wd, ID_TE, "Tex", 1, tex);
1286                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1287
1288                         /* direct data */
1289                         if(tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1290                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1291                         if(tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1292                         
1293                         write_previews(wd, tex->preview);
1294                 }
1295                 tex= tex->id.next;
1296         }
1297
1298         /* flush helps the compression for undo-save */
1299         mywrite(wd, MYWRITE_FLUSH, 0);
1300 }
1301
1302 static void write_materials(WriteData *wd, ListBase *idbase)
1303 {
1304         Material *ma;
1305         int a;
1306
1307         ma= idbase->first;
1308         while(ma) {
1309                 if(ma->id.us>0 || wd->current) {
1310                         /* write LibData */
1311                         writestruct(wd, ID_MA, "Material", 1, ma);
1312                         
1313                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1314                           of library blocks that implement this.*/
1315                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1316                           set yet :) */
1317                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1318
1319                         for(a=0; a<MAX_MTEX; a++) {
1320                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1321                         }
1322                         
1323                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1324                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1325                         
1326                         write_scriptlink(wd, &ma->scriptlink);
1327                         
1328                         /* nodetree is integral part of material, no libdata */
1329                         if(ma->nodetree) {
1330                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1331                                 write_nodetree(wd, ma->nodetree);
1332                         }
1333
1334                         write_previews(wd, ma->preview);                        
1335                 }
1336                 ma= ma->id.next;
1337         }
1338 }
1339
1340 static void write_worlds(WriteData *wd, ListBase *idbase)
1341 {
1342         World *wrld;
1343         int a;
1344
1345         wrld= idbase->first;
1346         while(wrld) {
1347                 if(wrld->id.us>0 || wd->current) {
1348                         /* write LibData */
1349                         writestruct(wd, ID_WO, "World", 1, wrld);
1350                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1351
1352                         for(a=0; a<MAX_MTEX; a++) {
1353                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1354                         }
1355
1356                         write_scriptlink(wd, &wrld->scriptlink);
1357
1358                         write_previews(wd, wrld->preview);
1359
1360                 }
1361                 wrld= wrld->id.next;
1362         }
1363 }
1364
1365 static void write_lamps(WriteData *wd, ListBase *idbase)
1366 {
1367         Lamp *la;
1368         int a;
1369
1370         la= idbase->first;
1371         while(la) {
1372                 if(la->id.us>0 || wd->current) {
1373                         /* write LibData */
1374                         writestruct(wd, ID_LA, "Lamp", 1, la);
1375                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1376
1377                         /* direct data */
1378                         for(a=0; a<MAX_MTEX; a++) {
1379                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1380                         }
1381
1382                         if(la->curfalloff)
1383                                 write_curvemapping(wd, la->curfalloff); 
1384                         
1385                         write_scriptlink(wd, &la->scriptlink);
1386
1387                         write_previews(wd, la->preview);
1388
1389                 }
1390                 la= la->id.next;
1391         }
1392 }
1393
1394
1395 static void write_scenes(WriteData *wd, ListBase *scebase)
1396 {
1397         Scene *sce;
1398         Base *base;
1399         Editing *ed;
1400         Sequence *seq;
1401         MetaStack *ms;
1402         Strip *strip;
1403         TimeMarker *marker;
1404         SceneRenderLayer *srl;
1405         int a;
1406         
1407         sce= scebase->first;
1408         while(sce) {
1409                 /* write LibData */
1410                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1411                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1412
1413                 /* direct data */
1414                 base= sce->base.first;
1415                 while(base) {
1416                         writestruct(wd, DATA, "Base", 1, base);
1417                         base= base->next;
1418                 }
1419
1420                 writestruct(wd, DATA, "Radio", 1, sce->radio);
1421                 writestruct(wd, DATA, "ToolSettings", 1, sce->toolsettings);
1422
1423                 for(a=0; a<MAX_MTEX; ++a)
1424                         writestruct(wd, DATA, "MTex", 1, sce->sculptdata.mtex[a]);
1425                 if(sce->sculptdata.cumap)
1426                         write_curvemapping(wd, sce->sculptdata.cumap);
1427
1428                 ed= sce->ed;
1429                 if(ed) {
1430                         writestruct(wd, DATA, "Editing", 1, ed);
1431
1432                         /* reset write flags too */
1433                         WHILE_SEQ(&ed->seqbase) {
1434                                 if(seq->strip) seq->strip->done= 0;
1435                                 writestruct(wd, DATA, "Sequence", 1, seq);
1436                         }
1437                         END_SEQ
1438
1439                         WHILE_SEQ(&ed->seqbase) {
1440                                 if(seq->strip && seq->strip->done==0) {
1441                                         /* write strip with 'done' at 0 because readfile */
1442
1443                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1444                                         if(seq->effectdata) {
1445                                                 switch(seq->type){
1446                                                 case SEQ_COLOR:
1447                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
1448                                                         break;
1449                                                 case SEQ_SPEED:
1450                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
1451                                                         break;
1452                                                 case SEQ_WIPE:
1453                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1454                                                         break;
1455                                                 case SEQ_GLOW:
1456                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1457                                                         break;
1458                                                 case SEQ_TRANSFORM:
1459                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
1460                                                         break;
1461                                                 }
1462                                         }
1463
1464                                         strip= seq->strip;
1465                                         writestruct(wd, DATA, "Strip", 1, strip);
1466                                         if(seq->flag & SEQ_USE_CROP && strip->crop) {
1467                                                 writestruct(wd, DATA, "StripCrop", 1, strip->crop);
1468                                         }
1469                                         if(seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
1470                                                 writestruct(wd, DATA, "StripTransform", 1, strip->transform);
1471                                         }
1472                                         if(seq->flag & SEQ_USE_PROXY && strip->proxy) {
1473                                                 writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
1474                                         }
1475                                         if(seq->type==SEQ_IMAGE)
1476                                                 writestruct(wd, DATA, "StripElem", strip->len, strip->stripdata);
1477                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
1478                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1479
1480                                         strip->done= 1;
1481                                 }
1482                         }
1483                         END_SEQ
1484                                 
1485                         /* new; meta stack too, even when its nasty restore code */
1486                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1487                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1488                         }
1489                 }
1490
1491                 write_scriptlink(wd, &sce->scriptlink);
1492
1493                 if (sce->r.avicodecdata) {
1494                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1495                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1496                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1497                 }
1498
1499                 if (sce->r.qtcodecdata) {
1500                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1501                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1502                 }
1503
1504                 /* writing dynamic list of TimeMarkers to the blend file */
1505                 for(marker= sce->markers.first; marker; marker= marker->next)
1506                         writestruct(wd, DATA, "TimeMarker", 1, marker);
1507                 
1508                 for(srl= sce->r.layers.first; srl; srl= srl->next)
1509                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
1510                 
1511                 if(sce->nodetree) {
1512                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
1513                         write_nodetree(wd, sce->nodetree);
1514                 }
1515                 
1516                 sce= sce->id.next;
1517         }
1518         /* flush helps the compression for undo-save */
1519         mywrite(wd, MYWRITE_FLUSH, 0);
1520 }
1521
1522 static void write_screens(WriteData *wd, ListBase *scrbase)
1523 {
1524         bScreen *sc;
1525         ScrArea *sa;
1526         ScrVert *sv;
1527         ScrEdge *se;
1528
1529         sc= scrbase->first;
1530         while(sc) {
1531                 /* write LibData */
1532                 writestruct(wd, ID_SCR, "Screen", 1, sc);
1533                 if (sc->id.properties) IDP_WriteProperty(sc->id.properties, wd);
1534
1535                 /* direct data */
1536                 sv= sc->vertbase.first;
1537                 while(sv) {
1538                         writestruct(wd, DATA, "ScrVert", 1, sv);
1539                         sv= sv->next;
1540                 }
1541
1542                 se= sc->edgebase.first;
1543                 while(se) {
1544                         writestruct(wd, DATA, "ScrEdge", 1, se);
1545                         se= se->next;
1546                 }
1547
1548                 sa= sc->areabase.first;
1549                 while(sa) {
1550                         SpaceLink *sl;
1551                         Panel *pa;
1552
1553                         writestruct(wd, DATA, "ScrArea", 1, sa);
1554
1555                         pa= sa->panels.first;
1556                         while(pa) {
1557                                 writestruct(wd, DATA, "Panel", 1, pa);
1558                                 pa= pa->next;
1559                         }
1560
1561                         /* space handler scriptlinks */
1562                         write_scriptlink(wd, &sa->scriptlink);
1563
1564                         sl= sa->spacedata.first;
1565                         while(sl) {
1566                                 if(sl->spacetype==SPACE_VIEW3D) {
1567                                         View3D *v3d= (View3D*) sl;
1568                                         writestruct(wd, DATA, "View3D", 1, v3d);
1569                                         if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
1570                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
1571                                         if(v3d->clipbb) writestruct(wd, DATA, "BoundBox", 1, v3d->clipbb);
1572                                 }
1573                                 else if(sl->spacetype==SPACE_IPO) {
1574                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
1575                                 }
1576                                 else if(sl->spacetype==SPACE_BUTS) {
1577                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
1578                                 }
1579                                 else if(sl->spacetype==SPACE_FILE) {
1580                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
1581                                 }
1582                                 else if(sl->spacetype==SPACE_SEQ) {
1583                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
1584                                 }
1585                                 else if(sl->spacetype==SPACE_OOPS) {
1586                                         SpaceOops *so= (SpaceOops *)sl;
1587                                         Oops *oops;
1588
1589                                         /* cleanup */
1590                                         oops= so->oops.first;
1591                                         while(oops) {
1592                                                 Oops *oopsn= oops->next;
1593                                                 if(oops->id==0) {
1594                                                         BLI_remlink(&so->oops, oops);
1595                                                         free_oops(oops);
1596                                                 }
1597                                                 oops= oopsn;
1598                                         }
1599
1600                                         /* ater cleanup, because of listbase! */
1601                                         writestruct(wd, DATA, "SpaceOops", 1, so);
1602
1603                                         oops= so->oops.first;
1604                                         while(oops) {
1605                                                 writestruct(wd, DATA, "Oops", 1, oops);
1606                                                 oops= oops->next;
1607                                         }
1608                                         /* outliner */
1609                                         if(so->treestore) {
1610                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
1611                                                 if(so->treestore->data)
1612                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
1613                                         }
1614                                 }
1615                                 else if(sl->spacetype==SPACE_IMAGE) {
1616                                         SpaceImage *sima= (SpaceImage *)sl;
1617                                         
1618                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
1619                                         if(sima->cumap)
1620                                                 write_curvemapping(wd, sima->cumap);                                    
1621                                 }
1622                                 else if(sl->spacetype==SPACE_IMASEL) {
1623                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
1624                                 }
1625                                 else if(sl->spacetype==SPACE_TEXT) {
1626                                         writestruct(wd, DATA, "SpaceText", 1, sl);
1627                                 }
1628                                 else if(sl->spacetype==SPACE_SCRIPT) {
1629                                         SpaceScript *sc = (SpaceScript*)sl;
1630                                         sc->but_refs = NULL;
1631                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
1632                                 }
1633                                 else if(sl->spacetype==SPACE_ACTION) {
1634                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
1635                                 }
1636                                 else if(sl->spacetype==SPACE_SOUND) {
1637                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
1638                                 }
1639                                 else if(sl->spacetype==SPACE_NLA){
1640                                         writestruct(wd, DATA, "SpaceNla", 1, sl);
1641                                 }
1642                                 else if(sl->spacetype==SPACE_TIME){
1643                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
1644                                 }
1645                                 else if(sl->spacetype==SPACE_NODE){
1646                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
1647                                 }
1648                                 sl= sl->next;
1649                         }
1650
1651                         sa= sa->next;
1652                 }
1653
1654                 sc= sc->id.next;
1655         }
1656 }
1657
1658 static void write_libraries(WriteData *wd, Main *main)
1659 {
1660         ListBase *lbarray[30];
1661         ID *id;
1662         int a, tot, foundone;
1663
1664         for(; main; main= main->next) {
1665
1666                 a=tot= set_listbasepointers(main, lbarray);
1667
1668                 /* test: is lib being used */
1669                 foundone= 0;
1670                 while(tot--) {
1671                         for(id= lbarray[tot]->first; id; id= id->next) {
1672                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
1673                                         foundone= 1;
1674                                         break;
1675                                 }
1676                         }
1677                         if(foundone) break;
1678                 }
1679
1680                 if(foundone) {
1681                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
1682
1683                         while(a--) {
1684                                 for(id= lbarray[a]->first; id; id= id->next) {
1685                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
1686                                                 writestruct(wd, ID_ID, "ID", 1, id);
1687                                         }
1688                                 }
1689                         }
1690                 }
1691         }
1692 }
1693
1694 static void write_bone(WriteData *wd, Bone* bone)
1695 {
1696         Bone*   cbone;
1697
1698         // PATCH for upward compatibility after 2.37+ armature recode
1699         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
1700                 
1701         // Write this bone
1702         writestruct(wd, DATA, "Bone", 1, bone);
1703         
1704         // Write Children
1705         cbone= bone->childbase.first;
1706         while(cbone) {
1707                 write_bone(wd, cbone);
1708                 cbone= cbone->next;
1709         }
1710 }
1711
1712 static void write_armatures(WriteData *wd, ListBase *idbase)
1713 {
1714         bArmature       *arm;
1715         Bone            *bone;
1716
1717         arm=idbase->first;
1718         while (arm) {
1719                 if (arm->id.us>0 || wd->current) {
1720                         writestruct(wd, ID_AR, "bArmature", 1, arm);
1721                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
1722
1723                         /* Direct data */
1724                         bone= arm->bonebase.first;
1725                         while(bone) {
1726                                 write_bone(wd, bone);
1727                                 bone=bone->next;
1728                         }
1729                 }
1730                 arm=arm->id.next;
1731         }
1732
1733         /* flush helps the compression for undo-save */
1734         mywrite(wd, MYWRITE_FLUSH, 0);
1735 }
1736
1737 static void write_actions(WriteData *wd, ListBase *idbase)
1738 {
1739         bAction                 *act;
1740         bActionChannel  *chan;
1741         TimeMarker *marker;
1742         
1743         for(act=idbase->first; act; act= act->id.next) {
1744                 if (act->id.us>0 || wd->current) {
1745                         writestruct(wd, ID_AC, "bAction", 1, act);
1746                         if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
1747                         
1748                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1749                                 writestruct(wd, DATA, "bActionChannel", 1, chan);
1750                                 write_constraint_channels(wd, &chan->constraintChannels);
1751                         }
1752                         
1753                         for (marker=act->markers.first; marker; marker=marker->next) {
1754                                 writestruct(wd, DATA, "TimeMarker", 1, marker);
1755                         }
1756                 }
1757         }
1758 }
1759
1760 static void write_texts(WriteData *wd, ListBase *idbase)
1761 {
1762         Text *text;
1763         TextLine *tmp;
1764
1765         text= idbase->first;
1766         while(text) {
1767                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
1768
1769                 /* write LibData */
1770                 writestruct(wd, ID_TXT, "Text", 1, text);
1771                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
1772                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
1773
1774                 if(!(text->flags & TXT_ISEXT)) {
1775                         /* now write the text data, in two steps for optimization in the readfunction */
1776                         tmp= text->lines.first;
1777                         while (tmp) {
1778                                 writestruct(wd, DATA, "TextLine", 1, tmp);
1779                                 tmp= tmp->next;
1780                         }
1781
1782                         tmp= text->lines.first;
1783                         while (tmp) {
1784                                 writedata(wd, DATA, tmp->len+1, tmp->line);
1785                                 tmp= tmp->next;
1786                         }
1787                 }
1788                 text= text->id.next;
1789         }
1790
1791         /* flush helps the compression for undo-save */
1792         mywrite(wd, MYWRITE_FLUSH, 0);
1793 }
1794
1795 static void write_sounds(WriteData *wd, ListBase *idbase)
1796 {
1797         bSound *sound;
1798         bSample *sample;
1799
1800         PackedFile * pf;
1801
1802         // set all samples to unsaved status
1803
1804         sample = samples->first; // samples is a global defined in sound.c
1805         while (sample) {
1806                 sample->flags |= SAMPLE_NEEDS_SAVE;
1807                 sample = sample->id.next;
1808         }
1809
1810         sound= idbase->first;
1811         while(sound) {
1812                 if(sound->id.us>0 || wd->current) {
1813                         // do we need to save the packedfile as well ?
1814                         sample = sound->sample;
1815                         if (sample) {
1816                                 if (sample->flags & SAMPLE_NEEDS_SAVE) {
1817                                         sound->newpackedfile = sample->packedfile;
1818                                         sample->flags &= ~SAMPLE_NEEDS_SAVE;
1819                                 } else {
1820                                         sound->newpackedfile = NULL;
1821                                 }
1822                         }
1823
1824                         /* write LibData */
1825                         writestruct(wd, ID_SO, "bSound", 1, sound);
1826                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
1827
1828                         if (sound->newpackedfile) {
1829                                 pf = sound->newpackedfile;
1830                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1831                                 writedata(wd, DATA, pf->size, pf->data);
1832                         }
1833
1834                         if (sample) {
1835                                 sound->newpackedfile = sample->packedfile;
1836                         }
1837                 }
1838                 sound= sound->id.next;
1839         }
1840
1841         /* flush helps the compression for undo-save */
1842         mywrite(wd, MYWRITE_FLUSH, 0);
1843 }
1844
1845 static void write_groups(WriteData *wd, ListBase *idbase)
1846 {
1847         Group *group;
1848         GroupObject *go;
1849
1850         for(group= idbase->first; group; group= group->id.next) {
1851                 if(group->id.us>0 || wd->current) {
1852                         /* write LibData */
1853                         writestruct(wd, ID_GR, "Group", 1, group);
1854                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
1855
1856                         go= group->gobject.first;
1857                         while(go) {
1858                                 writestruct(wd, DATA, "GroupObject", 1, go);
1859                                 go= go->next;
1860                         }
1861                 }
1862         }
1863 }
1864
1865 static void write_nodetrees(WriteData *wd, ListBase *idbase)
1866 {
1867         bNodeTree *ntree;
1868         
1869         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
1870                 if (ntree->id.us>0 || wd->current) {
1871                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
1872                         write_nodetree(wd, ntree);
1873                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
1874                 }
1875         }
1876 }
1877
1878 static void write_brushes(WriteData *wd, ListBase *idbase)
1879 {
1880         Brush *brush;
1881         int a;
1882         
1883         for(brush=idbase->first; brush; brush= brush->id.next) {
1884                 if(brush->id.us>0 || wd->current) {
1885                         writestruct(wd, ID_BR, "Brush", 1, brush);
1886                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
1887                         for(a=0; a<MAX_MTEX; a++)
1888                                 if(brush->mtex[a])
1889                                         writestruct(wd, DATA, "MTex", 1, brush->mtex[a]);
1890                 }
1891         }
1892 }
1893
1894 static void write_global(WriteData *wd)
1895 {
1896         FileGlobal fg;
1897         char subvstr[8];
1898         
1899         fg.curscreen= G.curscreen;
1900         fg.curscene= G.scene;
1901         fg.displaymode= G.displaymode;
1902         fg.winpos= G.winpos;
1903         fg.fileflags= (G.fileflags & ~G_FILE_NO_UI);    // prevent to save this, is not good convention, and feature with concerns...
1904         fg.globalf= G.f;
1905
1906         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
1907         memcpy(fg.subvstr, subvstr, 4);
1908         
1909         fg.subversion= BLENDER_SUBVERSION;
1910         fg.minversion= BLENDER_MINVERSION;
1911         fg.minsubversion= BLENDER_MINSUBVERSION;
1912         
1913         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
1914 }
1915
1916 /* if MemFile * there's filesave to memory */
1917 static int write_file_handle(int handle, MemFile *compare, MemFile *current, int write_user_block, int write_flags)
1918 {
1919         BHead bhead;
1920         ListBase mainlist;
1921         char buf[16];
1922         WriteData *wd;
1923
1924         blo_split_main(&mainlist, G.main);
1925
1926         wd= bgnwrite(handle, compare, current, write_flags);
1927         
1928         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (G.order==B_ENDIAN)?'V':'v', G.version);
1929         mywrite(wd, buf, 12);
1930
1931         write_renderinfo(wd);
1932         write_global(wd);
1933
1934         if(current==NULL)
1935                 write_screens  (wd, &G.main->screen);   /* no UI save in undo */
1936         write_scenes   (wd, &G.main->scene);
1937         write_curves   (wd, &G.main->curve);
1938         write_mballs   (wd, &G.main->mball);
1939         write_images   (wd, &G.main->image);
1940         write_cameras  (wd, &G.main->camera);
1941         write_lamps    (wd, &G.main->lamp);
1942         write_lattices (wd, &G.main->latt);
1943         write_vfonts   (wd, &G.main->vfont);
1944         write_ipos     (wd, &G.main->ipo);
1945         write_keys     (wd, &G.main->key);
1946         write_worlds   (wd, &G.main->world);
1947         write_texts    (wd, &G.main->text);
1948         write_sounds   (wd, &G.main->sound);
1949         write_groups   (wd, &G.main->group);
1950         write_armatures(wd, &G.main->armature);
1951         write_actions  (wd, &G.main->action);
1952         write_objects  (wd, &G.main->object);
1953         write_materials(wd, &G.main->mat);
1954         write_textures (wd, &G.main->tex);
1955         write_meshs    (wd, &G.main->mesh);
1956         write_particlesettings(wd, &G.main->particle);
1957         write_nodetrees(wd, &G.main->nodetree);
1958         write_brushes  (wd, &G.main->brush);
1959         if(current==NULL)       
1960                 write_libraries(wd,  G.main->next); /* no library save in undo */
1961
1962         if (write_user_block) {
1963                 write_userdef(wd);
1964         }
1965
1966         /* dna as last, because (to be implemented) test for which structs are written */
1967         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
1968
1969         /* end of file */
1970         memset(&bhead, 0, sizeof(BHead));
1971         bhead.code= ENDB;
1972         mywrite(wd, &bhead, sizeof(BHead));
1973
1974         blo_join_main(&mainlist);
1975         G.main= mainlist.first;
1976
1977         return endwrite(wd);
1978 }
1979
1980 /* return: success (1) */
1981 int BLO_write_file(char *dir, int write_flags, char **error_r)
1982 {
1983         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
1984         char tempname[FILE_MAXDIR+FILE_MAXFILE];
1985         int file, err, write_user_block;
1986
1987         sprintf(tempname, "%s@", dir);
1988
1989         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
1990         if(file == -1) {
1991                 *error_r= "Unable to open";
1992                 return 0;
1993         }
1994
1995         BLI_make_file_string(G.sce, userfilename, BLI_gethome(), ".B.blend");
1996
1997         write_user_block= BLI_streq(dir, userfilename);
1998
1999         err= write_file_handle(file, NULL,NULL, write_user_block, write_flags);
2000         close(file);
2001
2002         if(!err) {
2003                 if(write_flags & G_FILE_COMPRESS)
2004                 {       
2005                         // compressed files have the same ending as regular files... only from 2.4!!!
2006                         
2007                         int ret = BLI_gzip(tempname, dir);
2008                         
2009                         if(-1==ret) {
2010                                 *error_r= "Failed opening .gz file";
2011                                 return 0;
2012                         }
2013                         if(-2==ret) {
2014                                 *error_r= "Failed opening .blend file for compression";
2015                                 return 0;
2016                         }
2017                 }
2018                 else
2019                 if(BLI_rename(tempname, dir) < 0) {
2020                         *error_r= "Can't change old file. File saved with @";
2021                         return 0;
2022                 }
2023
2024                 
2025         } else {
2026                 *error_r= strerror(errno);
2027                 remove(tempname);
2028
2029                 return 0;
2030         }
2031
2032         return 1;
2033 }
2034
2035 /* return: success (1) */
2036 int BLO_write_file_mem(MemFile *compare, MemFile *current, int write_flags, char **error_r)
2037 {
2038         int err;
2039
2040         err= write_file_handle(0, compare, current, 0, write_flags);
2041         
2042         if(err==0) return 1;
2043         return 0;
2044 }
2045
2046
2047         /* Runtime writing */
2048
2049 #ifdef WIN32
2050 #define PATHSEPERATOR           "\\"
2051 #else
2052 #define PATHSEPERATOR           "/"
2053 #endif
2054
2055 static char *get_install_dir(void) {
2056         extern char bprogname[];
2057         char *tmpname = BLI_strdup(bprogname);
2058         char *cut;
2059
2060 #ifdef __APPLE__
2061         cut = strstr(tmpname, ".app");
2062         if (cut) cut[0] = 0;
2063 #endif
2064
2065         cut = BLI_last_slash(tmpname);
2066
2067         if (cut) {
2068                 cut[0] = 0;
2069                 return tmpname;
2070         } else {
2071                 MEM_freeN(tmpname);
2072                 return NULL;
2073         }
2074 }
2075
2076 static char *get_runtime_path(char *exename) {
2077         char *installpath= get_install_dir();
2078
2079         if (!installpath) {
2080                 return NULL;
2081         } else {
2082                 char *path= MEM_mallocN(strlen(installpath)+strlen(PATHSEPERATOR)+strlen(exename)+1, "runtimepath");
2083
2084                 if (path == NULL) {
2085                         MEM_freeN(installpath);
2086                         return NULL;
2087                 }
2088
2089                 strcpy(path, installpath);
2090                 strcat(path, PATHSEPERATOR);
2091                 strcat(path, exename);
2092
2093                 MEM_freeN(installpath);
2094
2095                 return path;
2096         }
2097 }
2098
2099 #ifdef __APPLE__
2100
2101 static int recursive_copy_runtime(char *outname, char *exename, char **cause_r) 
2102 {
2103         char *cause = NULL, *runtime = get_runtime_path(exename);
2104         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
2105         int progfd = -1;
2106
2107         if (!runtime) {
2108                 cause= "Unable to find runtime";
2109                 goto cleanup;
2110         }
2111         //printf("runtimepath %s\n", runtime);
2112                 
2113         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2114         if (progfd==-1) {
2115                 cause= "Unable to find runtime";
2116                 goto cleanup;
2117         }
2118
2119         sprintf(command, "/bin/cp -R \"%s\" \"%s\"", runtime, outname);
2120         //printf("command %s\n", command);
2121         if (system(command) == -1) {
2122                 cause = "Couldn't copy runtime";
2123         }
2124
2125 cleanup:
2126         if (progfd!=-1)
2127                 close(progfd);
2128         if (runtime)
2129                 MEM_freeN(runtime);
2130
2131         if (cause) {
2132                 *cause_r= cause;
2133                 return 0;
2134         } else
2135                 return 1;
2136 }
2137
2138 void BLO_write_runtime(char *file, char *exename) {
2139         char gamename[FILE_MAXDIR+FILE_MAXFILE];
2140         int outfd = -1;
2141         char *cause= NULL;
2142
2143         // remove existing file / bundle
2144         //printf("Delete file %s\n", file);
2145         BLI_delete(file, 0, TRUE);
2146
2147         if (!recursive_copy_runtime(file, exename, &cause))
2148                 goto cleanup;
2149
2150         strcpy(gamename, file);
2151         strcat(gamename, "/Contents/Resources/game.blend");
2152         //printf("gamename %s\n", gamename);
2153         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2154         if (outfd != -1) {
2155
2156                 write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
2157
2158                 if (write(outfd, " ", 1) != 1) {
2159                         cause= "Unable to write to output file";
2160                         goto cleanup;
2161                 }
2162         } else {
2163                 cause = "Unable to open blenderfile";
2164         }
2165
2166 cleanup:
2167         if (outfd!=-1)
2168                 close(outfd);
2169
2170         if (cause)
2171                 error("Unable to make runtime: %s", cause);
2172 }
2173
2174 #else /* !__APPLE__ */
2175
2176 static int handle_append_runtime(int handle, char *exename, char **cause_r) {
2177         char *cause= NULL, *runtime= get_runtime_path(exename);
2178         unsigned char buf[1024];
2179         int count, progfd= -1;
2180
2181         if (!runtime) {
2182                 cause= "Unable to find runtime";
2183                 goto cleanup;
2184         }
2185
2186         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2187         if (progfd==-1) {
2188                 cause= "Unable to find runtime";
2189                 goto cleanup;
2190         }
2191
2192         while ((count= read(progfd, buf, sizeof(buf)))>0) {
2193                 if (write(handle, buf, count)!=count) {
2194                         cause= "Unable to write to output file";
2195                         goto cleanup;
2196                 }
2197         }
2198
2199 cleanup:
2200         if (progfd!=-1)
2201                 close(progfd);
2202         if (runtime)
2203                 MEM_freeN(runtime);
2204
2205         if (cause) {
2206                 *cause_r= cause;
2207                 return 0;
2208         } else
2209                 return 1;
2210 }
2211
2212 static int handle_write_msb_int(int handle, int i) {
2213         unsigned char buf[4];
2214         buf[0]= (i>>24)&0xFF;
2215         buf[1]= (i>>16)&0xFF;
2216         buf[2]= (i>>8)&0xFF;
2217         buf[3]= (i>>0)&0xFF;
2218
2219         return (write(handle, buf, 4)==4);
2220 }
2221
2222 void BLO_write_runtime(char *file, char *exename) {
2223         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2224         char *cause= NULL;
2225         int datastart;
2226
2227         if (!outfd) {
2228                 cause= "Unable to open output file";
2229                 goto cleanup;
2230         }
2231         if (!handle_append_runtime(outfd, exename, &cause))
2232                 goto cleanup;
2233
2234         datastart= lseek(outfd, 0, SEEK_CUR);
2235
2236         write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
2237
2238         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
2239                 cause= "Unable to write to output file";
2240                 goto cleanup;
2241         }
2242
2243 cleanup:
2244         if (outfd!=-1)
2245                 close(outfd);
2246
2247         if (cause)
2248                 error("Unable to make runtime: %s", cause);
2249 }
2250
2251 #endif /* !__APPLE__ */