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