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