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