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