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