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