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