svn merge -r 15590:15688 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[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                         writestruct(wd, DATA, "PartDeflect", 1, part->pd);
537                 }
538                 part= part->id.next;
539         }
540 }
541 static void write_particlesystems(WriteData *wd, ListBase *particles)
542 {
543         ParticleSystem *psys= particles->first;
544         int a;
545
546         for(; psys; psys=psys->next) {
547                 writestruct(wd, DATA, "ParticleSystem", 1, psys);
548
549                 if(psys->particles) {
550                         writestruct(wd, DATA, "ParticleData", psys->totpart ,psys->particles);
551
552                         if(psys->particles->hair) {
553                                 ParticleData *pa = psys->particles;
554
555                                 for(a=0; a<psys->totpart; a++, pa++)
556                                         writestruct(wd, DATA, "HairKey", pa->totkey, pa->hair);
557                         }
558                 }
559                 if(psys->child) writestruct(wd, DATA, "ChildParticle", psys->totchild ,psys->child);
560                 writestruct(wd, DATA, "SoftBody", 1, psys->soft);
561                 if(psys->soft) writestruct(wd, DATA, "PointCache", 1, psys->soft->pointcache);
562                 writestruct(wd, DATA, "PointCache", 1, psys->pointcache);
563         }
564 }
565
566 static void write_properties(WriteData *wd, ListBase *lb)
567 {
568         bProperty *prop;
569
570         prop= lb->first;
571         while(prop) {
572                 writestruct(wd, DATA, "bProperty", 1, prop);
573
574                 if(prop->poin && prop->poin != &prop->data)
575                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
576
577                 prop= prop->next;
578         }
579 }
580
581 static void write_sensors(WriteData *wd, ListBase *lb)
582 {
583         bSensor *sens;
584
585         sens= lb->first;
586         while(sens) {
587                 writestruct(wd, DATA, "bSensor", 1, sens);
588
589                 writedata(wd, DATA, sizeof(void *)*sens->totlinks, sens->links);
590
591                 switch(sens->type) {
592                 case SENS_NEAR:
593                         writestruct(wd, DATA, "bNearSensor", 1, sens->data);
594                         break;
595                 case SENS_MOUSE:
596                         writestruct(wd, DATA, "bMouseSensor", 1, sens->data);
597                         break;
598                 case SENS_TOUCH:
599                         writestruct(wd, DATA, "bTouchSensor", 1, sens->data);
600                         break;
601                 case SENS_KEYBOARD:
602                         writestruct(wd, DATA, "bKeyboardSensor", 1, sens->data);
603                         break;
604                 case SENS_PROPERTY:
605                         writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
606                         break;
607                 case SENS_ACTUATOR:
608                         writestruct(wd, DATA, "bActuatorSensor", 1, sens->data);
609                         break;
610                 case SENS_COLLISION:
611                         writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
612                         break;
613                 case SENS_RADAR:
614                         writestruct(wd, DATA, "bRadarSensor", 1, sens->data);
615                         break;
616                 case SENS_RANDOM:
617                         writestruct(wd, DATA, "bRandomSensor", 1, sens->data);
618                         break;
619                 case SENS_RAY:
620                         writestruct(wd, DATA, "bRaySensor", 1, sens->data);
621                         break;
622                 case SENS_MESSAGE:
623                         writestruct(wd, DATA, "bMessageSensor", 1, sens->data);
624                         break;
625                 case SENS_JOYSTICK:
626                         writestruct(wd, DATA, "bJoystickSensor", 1, sens->data);
627                         break;
628                 default:
629                         ; /* error: don't know how to write this file */
630                 }
631
632                 sens= sens->next;
633         }
634 }
635
636 static void write_controllers(WriteData *wd, ListBase *lb)
637 {
638         bController *cont;
639
640         cont= lb->first;
641         while(cont) {
642                 writestruct(wd, DATA, "bController", 1, cont);
643
644                 writedata(wd, DATA, sizeof(void *)*cont->totlinks, cont->links);
645
646                 switch(cont->type) {
647                 case CONT_EXPRESSION:
648                         writestruct(wd, DATA, "bExpressionCont", 1, cont->data);
649                         break;
650                 case CONT_PYTHON:
651                         writestruct(wd, DATA, "bPythonCont", 1, cont->data);
652                         break;
653                 default:
654                         ; /* error: don't know how to write this file */
655                 }
656
657                 cont= cont->next;
658         }
659 }
660
661 static void write_actuators(WriteData *wd, ListBase *lb)
662 {
663         bActuator *act;
664
665         act= lb->first;
666         while(act) {
667                 writestruct(wd, DATA, "bActuator", 1, act);
668
669                 switch(act->type) {
670                 case ACT_ACTION:
671                 case ACT_SHAPEACTION:
672                         writestruct(wd, DATA, "bActionActuator", 1, act->data);
673                         break;
674                 case ACT_SOUND:
675                         writestruct(wd, DATA, "bSoundActuator", 1, act->data);
676                         break;
677                 case ACT_CD:
678                         writestruct(wd, DATA, "bCDActuator", 1, act->data);
679                         break;
680                 case ACT_OBJECT:
681                         writestruct(wd, DATA, "bObjectActuator", 1, act->data);
682                         break;
683                 case ACT_IPO:
684                         writestruct(wd, DATA, "bIpoActuator", 1, act->data);
685                         break;
686                 case ACT_PROPERTY:
687                         writestruct(wd, DATA, "bPropertyActuator", 1, act->data);
688                         break;
689                 case ACT_CAMERA:
690                         writestruct(wd, DATA, "bCameraActuator", 1, act->data);
691                         break;
692                 case ACT_CONSTRAINT:
693                         writestruct(wd, DATA, "bConstraintActuator", 1, act->data);
694                         break;
695                 case ACT_EDIT_OBJECT:
696                         writestruct(wd, DATA, "bEditObjectActuator", 1, act->data);
697                         break;
698                 case ACT_SCENE:
699                         writestruct(wd, DATA, "bSceneActuator", 1, act->data);
700                         break;
701                 case ACT_GROUP:
702                         writestruct(wd, DATA, "bGroupActuator", 1, act->data);
703                         break;
704                 case ACT_RANDOM:
705                         writestruct(wd, DATA, "bRandomActuator", 1, act->data);
706                         break;
707                 case ACT_MESSAGE:
708                         writestruct(wd, DATA, "bMessageActuator", 1, act->data);
709                         break;
710                 case ACT_GAME:
711                         writestruct(wd, DATA, "bGameActuator", 1, act->data);
712                         break;
713                 case ACT_VISIBILITY:
714                         writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
715                         break;
716                 case ACT_2DFILTER:
717                         writestruct(wd, DATA, "bTwoDFilterActuator", 1, act->data);
718                         break;
719                 case ACT_PARENT:
720                         writestruct(wd, DATA, "bParentActuator", 1, act->data);
721                         break;
722                 case ACT_STATE:
723                         writestruct(wd, DATA, "bStateActuator", 1, act->data);
724                         break;
725                 default:
726                         ; /* error: don't know how to write this file */
727                 }
728
729                 act= act->next;
730         }
731 }
732
733 static void write_nlastrips(WriteData *wd, ListBase *nlabase)
734 {
735         bActionStrip *strip;
736         bActionModifier *amod;
737         
738         for (strip=nlabase->first; strip; strip=strip->next)
739                 writestruct(wd, DATA, "bActionStrip", 1, strip);
740         for (strip=nlabase->first; strip; strip=strip->next) {
741                 for(amod= strip->modifiers.first; amod; amod= amod->next)
742                         writestruct(wd, DATA, "bActionModifier", 1, amod);
743         }
744 }
745
746 static void write_constraints(WriteData *wd, ListBase *conlist)
747 {
748         bConstraint *con;
749
750         for (con=conlist->first; con; con=con->next) {
751                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
752                 
753                 /* Write the specific data */
754                 if (cti && con->data) {
755                         /* firstly, just write the plain con->data struct */
756                         writestruct(wd, DATA, cti->structName, 1, con->data);
757                         
758                         /* do any constraint specific stuff */
759                         switch (con->type) {
760                                 case CONSTRAINT_TYPE_PYTHON:
761                                 {
762                                         bPythonConstraint *data = (bPythonConstraint *)con->data;
763                                         bConstraintTarget *ct;
764                                         
765                                         /* write targets */
766                                         for (ct= data->targets.first; ct; ct= ct->next)
767                                                 writestruct(wd, DATA, "bConstraintTarget", 1, ct);
768                                         
769                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
770                                          of library blocks that implement this.*/
771                                         IDP_WriteProperty(data->prop, wd);
772                                 }
773                                 break;
774                         }
775                 }
776                 
777                 /* Write the constraint */
778                 writestruct(wd, DATA, "bConstraint", 1, con);
779         }
780 }
781
782 static void write_pose(WriteData *wd, bPose *pose)
783 {
784         bPoseChannel *chan;
785         bActionGroup *grp;
786
787         /* Write each channel */
788         if (!pose)
789                 return;
790
791         /* Write channels */
792         for (chan=pose->chanbase.first; chan; chan=chan->next) {
793                 write_constraints(wd, &chan->constraints);
794                 
795                 /* prevent crashes with autosave, when a bone duplicated in editmode has not yet been assigned to its posechannel */
796                 if (chan->bone) 
797                         chan->selectflag= chan->bone->flag & (BONE_SELECTED|BONE_ACTIVE); /* gets restored on read, for library armatures */
798                 
799                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
800         }
801         
802         /* Write groups */
803         for (grp=pose->agroups.first; grp; grp=grp->next) 
804                 writestruct(wd, DATA, "bActionGroup", 1, grp);
805
806         /* Write this pose */
807         writestruct(wd, DATA, "bPose", 1, pose);
808 }
809
810 static void write_defgroups(WriteData *wd, ListBase *defbase)
811 {
812         bDeformGroup    *defgroup;
813
814         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
815                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
816 }
817
818 static void write_constraint_channels(WriteData *wd, ListBase *chanbase)
819 {
820         bConstraintChannel *chan;
821
822         for (chan = chanbase->first; chan; chan=chan->next)
823                 writestruct(wd, DATA, "bConstraintChannel", 1, chan);
824
825 }
826
827 static void write_modifiers(WriteData *wd, ListBase *modbase)
828 {
829         ModifierData *md;
830
831         if (modbase == NULL) return;
832         for (md=modbase->first; md; md= md->next) {
833                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
834                 if (mti == NULL) return;
835                 
836                 writestruct(wd, DATA, mti->structName, 1, md);
837                         
838                 if (md->type==eModifierType_Hook) {
839                         HookModifierData *hmd = (HookModifierData*) md;
840                         
841                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
842                 }
843                 else if(md->type==eModifierType_Cloth) {
844                         ClothModifierData *clmd = (ClothModifierData*) md;
845                         
846                         writestruct(wd, DATA, "ClothSimSettings", 1, clmd->sim_parms);
847                         writestruct(wd, DATA, "ClothCollSettings", 1, clmd->coll_parms);
848                         writestruct(wd, DATA, "PointCache", 1, clmd->point_cache);
849                 } 
850                 else if (md->type==eModifierType_Collision) {
851                         
852                         /*
853                         CollisionModifierData *collmd = (CollisionModifierData*) md;
854                         // TODO: CollisionModifier should use pointcache 
855                         // + have proper reset events before enabling this
856                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->x);
857                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->xnew);
858                         writestruct(wd, DATA, "MFace", collmd->numfaces, collmd->mfaces);
859                         */
860                 }
861                 else if (md->type==eModifierType_MeshDeform) {
862                         MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
863                         int size = mmd->dyngridsize;
864
865                         writedata(wd, DATA, sizeof(float)*mmd->totvert*mmd->totcagevert,
866                                 mmd->bindweights);
867                         writedata(wd, DATA, sizeof(float)*3*mmd->totcagevert,
868                                 mmd->bindcos);
869                         writestruct(wd, DATA, "MDefCell", size*size*size, mmd->dyngrid);
870                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->dyninfluences);
871                         writedata(wd, DATA, sizeof(int)*mmd->totvert, mmd->dynverts);
872                 }
873         }
874 }
875
876 static void write_objects(WriteData *wd, ListBase *idbase)
877 {
878         Object *ob;
879         
880         ob= idbase->first;
881         while(ob) {
882                 if(ob->id.us>0 || wd->current) {
883                         /* write LibData */
884 #ifdef WITH_VERSE
885                         /* pointer at vnode stored in file have to be NULL */
886                         struct VNode *vnode = (VNode*)ob->vnode;
887                         if(vnode) ob->vnode = NULL;
888 #endif
889                         writestruct(wd, ID_OB, "Object", 1, ob);
890 #ifdef WITH_VERSE
891                         if(vnode) ob->vnode = (void*)vnode;
892 #endif
893
894                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
895                           of library blocks that implement this.*/
896                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
897
898                         /* direct data */
899                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
900                         /* write_effects(wd, &ob->effect); */ /* not used anymore */
901                         write_properties(wd, &ob->prop);
902                         write_sensors(wd, &ob->sensors);
903                         write_controllers(wd, &ob->controllers);
904                         write_actuators(wd, &ob->actuators);
905                         write_scriptlink(wd, &ob->scriptlink);
906                         write_pose(wd, ob->pose);
907                         write_defgroups(wd, &ob->defbase);
908                         write_constraints(wd, &ob->constraints);
909                         write_constraint_channels(wd, &ob->constraintChannels);
910                         write_nlastrips(wd, &ob->nlastrips);
911                         
912                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
913                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
914                         if(ob->soft) writestruct(wd, DATA, "PointCache", 1, ob->soft->pointcache);
915                         writestruct(wd, DATA, "FluidsimSettings", 1, ob->fluidsimSettings); // NT
916                         
917                         write_particlesystems(wd, &ob->particlesystem);
918                         write_modifiers(wd, &ob->modifiers);
919                 }
920                 ob= ob->id.next;
921         }
922
923         /* flush helps the compression for undo-save */
924         mywrite(wd, MYWRITE_FLUSH, 0);
925 }
926
927
928 static void write_vfonts(WriteData *wd, ListBase *idbase)
929 {
930         VFont *vf;
931         PackedFile * pf;
932
933         vf= idbase->first;
934         while(vf) {
935                 if(vf->id.us>0 || wd->current) {
936                         /* write LibData */
937                         writestruct(wd, ID_VF, "VFont", 1, vf);
938                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
939
940                         /* direct data */
941
942                         if (vf->packedfile) {
943                                 pf = vf->packedfile;
944                                 writestruct(wd, DATA, "PackedFile", 1, pf);
945                                 writedata(wd, DATA, pf->size, pf->data);
946                         }
947                 }
948
949                 vf= vf->id.next;
950         }
951 }
952
953 static void write_ipos(WriteData *wd, ListBase *idbase)
954 {
955         Ipo *ipo;
956         IpoCurve *icu;
957
958         ipo= idbase->first;
959         while(ipo) {
960                 if(ipo->id.us>0 || wd->current) {
961                         /* write LibData */
962                         writestruct(wd, ID_IP, "Ipo", 1, ipo);
963                         if (ipo->id.properties) IDP_WriteProperty(ipo->id.properties, wd);
964
965                         /* direct data */
966                         icu= ipo->curve.first;
967                         while(icu) {
968                                 writestruct(wd, DATA, "IpoCurve", 1, icu);
969                                 icu= icu->next;
970                         }
971
972                         icu= ipo->curve.first;
973                         while(icu) {
974                                 if(icu->bezt)  writestruct(wd, DATA, "BezTriple", icu->totvert, icu->bezt);
975                                 if(icu->bp)  writestruct(wd, DATA, "BPoint", icu->totvert, icu->bp);
976                                 if(icu->driver)  writestruct(wd, DATA, "IpoDriver", 1, icu->driver);
977                                 icu= icu->next;
978                         }
979                 }
980
981                 ipo= ipo->id.next;
982         }
983
984         /* flush helps the compression for undo-save */
985         mywrite(wd, MYWRITE_FLUSH, 0);
986 }
987
988 static void write_keys(WriteData *wd, ListBase *idbase)
989 {
990         Key *key;
991         KeyBlock *kb;
992
993         key= idbase->first;
994         while(key) {
995                 if(key->id.us>0 || wd->current) {
996                         /* write LibData */
997                         writestruct(wd, ID_KE, "Key", 1, key);
998                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
999
1000                         /* direct data */
1001                         kb= key->block.first;
1002                         while(kb) {
1003                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
1004                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
1005                                 kb= kb->next;
1006                         }
1007                 }
1008
1009                 key= key->id.next;
1010         }
1011         /* flush helps the compression for undo-save */
1012         mywrite(wd, MYWRITE_FLUSH, 0);
1013 }
1014
1015 static void write_cameras(WriteData *wd, ListBase *idbase)
1016 {
1017         Camera *cam;
1018
1019         cam= idbase->first;
1020         while(cam) {
1021                 if(cam->id.us>0 || wd->current) {
1022                         /* write LibData */
1023                         writestruct(wd, ID_CA, "Camera", 1, cam);
1024                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
1025
1026                         /* direct data */
1027                         write_scriptlink(wd, &cam->scriptlink);
1028                 }
1029
1030                 cam= cam->id.next;
1031         }
1032 }
1033
1034 static void write_mballs(WriteData *wd, ListBase *idbase)
1035 {
1036         MetaBall *mb;
1037         MetaElem *ml;
1038
1039         mb= idbase->first;
1040         while(mb) {
1041                 if(mb->id.us>0 || wd->current) {
1042                         /* write LibData */
1043                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
1044                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
1045
1046                         /* direct data */
1047                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
1048
1049                         ml= mb->elems.first;
1050                         while(ml) {
1051                                 writestruct(wd, DATA, "MetaElem", 1, ml);
1052                                 ml= ml->next;
1053                         }
1054                 }
1055                 mb= mb->id.next;
1056         }
1057 }
1058
1059 int amount_of_chars(char *str)
1060 {
1061         // Since the data is saved as UTF-8 to the cu->str
1062         // The cu->len is not same as the strlen(cu->str)
1063         return strlen(str);
1064 }
1065
1066 static void write_curves(WriteData *wd, ListBase *idbase)
1067 {
1068         Curve *cu;
1069         Nurb *nu;
1070
1071         cu= idbase->first;
1072         while(cu) {
1073                 if(cu->id.us>0 || wd->current) {
1074                         /* write LibData */
1075                         writestruct(wd, ID_CU, "Curve", 1, cu);
1076
1077                         /* direct data */
1078                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
1079                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
1080
1081                         if(cu->vfont) {
1082                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1083                                 writestruct(wd, DATA, "CharInfo", cu->len, cu->strinfo);
1084                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);                           
1085                         }
1086                         else {
1087                                 /* is also the order of reading */
1088                                 nu= cu->nurb.first;
1089                                 while(nu) {
1090                                         writestruct(wd, DATA, "Nurb", 1, nu);
1091                                         nu= nu->next;
1092                                 }
1093                                 nu= cu->nurb.first;
1094                                 while(nu) {
1095                                         if( (nu->type & 7)==CU_BEZIER)
1096                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1097                                         else {
1098                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1099                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1100                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1101                                         }
1102                                         nu= nu->next;
1103                                 }
1104                         }
1105                 }
1106                 cu= cu->id.next;
1107         }
1108
1109         /* flush helps the compression for undo-save */
1110         mywrite(wd, MYWRITE_FLUSH, 0);
1111 }
1112
1113 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1114 {
1115         if (dvlist) {
1116                 int     i;
1117                 
1118                 /* Write the dvert list */
1119                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1120                 
1121                 /* Write deformation data for each dvert */
1122                 for (i=0; i<count; i++) {
1123                         if (dvlist[i].dw)
1124                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1125                 }
1126         }
1127 }
1128
1129 static void write_customdata(WriteData *wd, int count, CustomData *data, int partial_type, int partial_count)
1130 {
1131         int i;
1132
1133         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1134
1135         for (i=0; i<data->totlayer; i++) {
1136                 CustomDataLayer *layer= &data->layers[i];
1137                 char *structname;
1138                 int structnum, datasize;
1139
1140                 if (layer->type == CD_MDEFORMVERT) {
1141                         /* layer types that allocate own memory need special handling */
1142                         write_dverts(wd, count, layer->data);
1143                 }
1144                 else {
1145                         CustomData_file_write_info(layer->type, &structname, &structnum);
1146                         if (structnum) {
1147                                 /* when using partial visibility, the MEdge and MFace layers
1148                                    are smaller than the original, so their type and count is
1149                                    passed to make this work */
1150                                 if (layer->type != partial_type) datasize= structnum*count;
1151                                 else datasize= structnum*partial_count;
1152
1153                                 writestruct(wd, DATA, structname, datasize, layer->data);
1154                         }
1155                         else
1156                                 printf("error: this CustomDataLayer must not be written to file\n");
1157                 }
1158         }
1159 }
1160
1161 static void write_meshs(WriteData *wd, ListBase *idbase)
1162 {
1163         Mesh *mesh;
1164         MultiresLevel *lvl;
1165
1166         mesh= idbase->first;
1167         while(mesh) {
1168                 if(mesh->id.us>0 || wd->current) {
1169                         /* write LibData */
1170 #ifdef WITH_VERSE
1171                         struct VNode *vnode = (VNode*)mesh->vnode;
1172                         if(vnode) {
1173                                 /* mesh has to be created from verse geometry node*/
1174                                 create_meshdata_from_geom_node(mesh, vnode);
1175                                 /* pointer at verse node can't be stored in file */
1176                                 mesh->vnode = NULL;
1177                         }
1178 #endif
1179
1180                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
1181 #ifdef WITH_VERSE
1182                         if(vnode) mesh->vnode = (void*)vnode;
1183 #endif
1184
1185                         /* direct data */
1186                         if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1187
1188                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1189
1190                         if(mesh->pv) {
1191                                 write_customdata(wd, mesh->pv->totvert, &mesh->vdata, -1, 0);
1192                                 write_customdata(wd, mesh->pv->totedge, &mesh->edata,
1193                                         CD_MEDGE, mesh->totedge);
1194                                 write_customdata(wd, mesh->pv->totface, &mesh->fdata,
1195                                         CD_MFACE, mesh->totface);
1196                         }
1197                         else {
1198                                 write_customdata(wd, mesh->totvert, &mesh->vdata, -1, 0);
1199                                 write_customdata(wd, mesh->totedge, &mesh->edata, -1, 0);
1200                                 write_customdata(wd, mesh->totface, &mesh->fdata, -1, 0);
1201                         }
1202
1203                         /* Multires data */
1204                         writestruct(wd, DATA, "Multires", 1, mesh->mr);
1205                         if(mesh->mr) {
1206                                 lvl= mesh->mr->levels.first;
1207                                 if(lvl) {
1208                                         write_customdata(wd, lvl->totvert, &mesh->mr->vdata, -1, 0);
1209                                         write_customdata(wd, lvl->totface, &mesh->mr->fdata, -1, 0);
1210                                         writedata(wd, DATA, sizeof(short)*lvl->totedge, mesh->mr->edge_flags);
1211                                         writedata(wd, DATA, sizeof(char)*lvl->totedge, mesh->mr->edge_creases);
1212                                 }
1213
1214                                 for(; lvl; lvl= lvl->next) {
1215                                         writestruct(wd, DATA, "MultiresLevel", 1, lvl);
1216                                         writestruct(wd, DATA, "MultiresFace", lvl->totface, lvl->faces);
1217                                         writestruct(wd, DATA, "MultiresEdge", lvl->totedge, lvl->edges);
1218                                         writestruct(wd, DATA, "MultiresColFace", lvl->totface, lvl->colfaces);
1219                                 }
1220
1221                                 lvl= mesh->mr->levels.last;
1222                                 if(lvl)
1223                                         writestruct(wd, DATA, "MVert", lvl->totvert, mesh->mr->verts);
1224                         }
1225
1226                         /* PMV data */
1227                         if(mesh->pv) {
1228                                 writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
1229                                 writedata(wd, DATA, sizeof(unsigned int)*mesh->pv->totvert, mesh->pv->vert_map);
1230                                 writedata(wd, DATA, sizeof(int)*mesh->pv->totedge, mesh->pv->edge_map);
1231                                 writestruct(wd, DATA, "MFace", mesh->pv->totface, mesh->pv->old_faces);
1232                                 writestruct(wd, DATA, "MEdge", mesh->pv->totedge, mesh->pv->old_edges);
1233                         }
1234                 }
1235                 mesh= mesh->id.next;
1236         }
1237 }
1238
1239 static void write_lattices(WriteData *wd, ListBase *idbase)
1240 {
1241         Lattice *lt;
1242         
1243         lt= idbase->first;
1244         while(lt) {
1245                 if(lt->id.us>0 || wd->current) {
1246                         /* write LibData */
1247                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1248                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1249
1250                         /* direct data */
1251                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1252                         
1253                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1254                         
1255                 }
1256                 lt= lt->id.next;
1257         }
1258 }
1259
1260 static void write_previews(WriteData *wd, PreviewImage *prv)
1261 {
1262         if (prv) {
1263                 short w = prv->w[1];
1264                 short h = prv->h[1];
1265                 unsigned int *rect = prv->rect[1];
1266                 /* don't write out large previews if not requested */
1267                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1268                         prv->w[1] = 0;
1269                         prv->h[1] = 0;
1270                         prv->rect[1] = NULL;
1271                 }
1272                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1273                 if (prv->rect[0]) writedata(wd, DATA, prv->w[0]*prv->h[0]*sizeof(unsigned int), prv->rect[0]);
1274                 if (prv->rect[1]) writedata(wd, DATA, prv->w[1]*prv->h[1]*sizeof(unsigned int), prv->rect[1]);
1275
1276                 /* restore preview, we still want to keep it in memory even if not saved to file */
1277                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1278                         prv->w[1] = w;
1279                         prv->h[1] = h;
1280                         prv->rect[1] = rect;
1281                 }
1282         }
1283 }
1284
1285 static void write_images(WriteData *wd, ListBase *idbase)
1286 {
1287         Image *ima;
1288         PackedFile * pf;
1289
1290
1291         ima= idbase->first;
1292         while(ima) {
1293                 if(ima->id.us>0 || wd->current) {
1294                         /* write LibData */
1295                         writestruct(wd, ID_IM, "Image", 1, ima);
1296                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1297
1298                         if (ima->packedfile) {
1299                                 pf = ima->packedfile;
1300                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1301                                 writedata(wd, DATA, pf->size, pf->data);
1302                         }
1303
1304                         write_previews(wd, ima->preview);
1305
1306                         }
1307                 ima= ima->id.next;
1308         }
1309         /* flush helps the compression for undo-save */
1310         mywrite(wd, MYWRITE_FLUSH, 0);
1311 }
1312
1313 static void write_textures(WriteData *wd, ListBase *idbase)
1314 {
1315         Tex *tex;
1316
1317         tex= idbase->first;
1318         while(tex) {
1319                 if(tex->id.us>0 || wd->current) {
1320                         /* write LibData */
1321                         writestruct(wd, ID_TE, "Tex", 1, tex);
1322                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1323
1324                         /* direct data */
1325                         if(tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1326                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1327                         if(tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1328                         
1329                         write_previews(wd, tex->preview);
1330                 }
1331                 tex= tex->id.next;
1332         }
1333
1334         /* flush helps the compression for undo-save */
1335         mywrite(wd, MYWRITE_FLUSH, 0);
1336 }
1337
1338 static void write_materials(WriteData *wd, ListBase *idbase)
1339 {
1340         Material *ma;
1341         int a;
1342
1343         ma= idbase->first;
1344         while(ma) {
1345                 if(ma->id.us>0 || wd->current) {
1346                         /* write LibData */
1347                         writestruct(wd, ID_MA, "Material", 1, ma);
1348                         
1349                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1350                           of library blocks that implement this.*/
1351                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1352                           set yet :) */
1353                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1354
1355                         for(a=0; a<MAX_MTEX; a++) {
1356                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1357                         }
1358                         
1359                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1360                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1361                         
1362                         write_scriptlink(wd, &ma->scriptlink);
1363                         
1364                         /* nodetree is integral part of material, no libdata */
1365                         if(ma->nodetree) {
1366                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1367                                 write_nodetree(wd, ma->nodetree);
1368                         }
1369
1370                         write_previews(wd, ma->preview);                        
1371                 }
1372                 ma= ma->id.next;
1373         }
1374 }
1375
1376 static void write_worlds(WriteData *wd, ListBase *idbase)
1377 {
1378         World *wrld;
1379         int a;
1380
1381         wrld= idbase->first;
1382         while(wrld) {
1383                 if(wrld->id.us>0 || wd->current) {
1384                         /* write LibData */
1385                         writestruct(wd, ID_WO, "World", 1, wrld);
1386                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1387
1388                         for(a=0; a<MAX_MTEX; a++) {
1389                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1390                         }
1391
1392                         write_scriptlink(wd, &wrld->scriptlink);
1393
1394                         write_previews(wd, wrld->preview);
1395
1396                 }
1397                 wrld= wrld->id.next;
1398         }
1399 }
1400
1401 static void write_lamps(WriteData *wd, ListBase *idbase)
1402 {
1403         Lamp *la;
1404         int a;
1405
1406         la= idbase->first;
1407         while(la) {
1408                 if(la->id.us>0 || wd->current) {
1409                         /* write LibData */
1410                         writestruct(wd, ID_LA, "Lamp", 1, la);
1411                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1412
1413                         /* direct data */
1414                         for(a=0; a<MAX_MTEX; a++) {
1415                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1416                         }
1417
1418                         if(la->curfalloff)
1419                                 write_curvemapping(wd, la->curfalloff); 
1420                         
1421                         write_scriptlink(wd, &la->scriptlink);
1422
1423                         write_previews(wd, la->preview);
1424
1425                 }
1426                 la= la->id.next;
1427         }
1428 }
1429
1430
1431 static void write_scenes(WriteData *wd, ListBase *scebase)
1432 {
1433         Scene *sce;
1434         Base *base;
1435         Editing *ed;
1436         Sequence *seq;
1437         MetaStack *ms;
1438         Strip *strip;
1439         TimeMarker *marker;
1440         TransformOrientation *ts;
1441         SceneRenderLayer *srl;
1442         int a;
1443         
1444         sce= scebase->first;
1445         while(sce) {
1446                 /* write LibData */
1447                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1448                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1449
1450                 /* direct data */
1451                 base= sce->base.first;
1452                 while(base) {
1453                         writestruct(wd, DATA, "Base", 1, base);
1454                         base= base->next;
1455                 }
1456
1457                 writestruct(wd, DATA, "Radio", 1, sce->radio);
1458                 writestruct(wd, DATA, "ToolSettings", 1, sce->toolsettings);
1459
1460                 for(a=0; a<MAX_MTEX; ++a)
1461                         writestruct(wd, DATA, "MTex", 1, sce->sculptdata.mtex[a]);
1462                 if(sce->sculptdata.cumap)
1463                         write_curvemapping(wd, sce->sculptdata.cumap);
1464
1465                 ed= sce->ed;
1466                 if(ed) {
1467                         writestruct(wd, DATA, "Editing", 1, ed);
1468
1469                         /* reset write flags too */
1470                         WHILE_SEQ(&ed->seqbase) {
1471                                 if(seq->strip) seq->strip->done= 0;
1472                                 writestruct(wd, DATA, "Sequence", 1, seq);
1473                         }
1474                         END_SEQ
1475
1476                         WHILE_SEQ(&ed->seqbase) {
1477                                 if(seq->strip && seq->strip->done==0) {
1478                                         /* write strip with 'done' at 0 because readfile */
1479
1480                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1481                                         if(seq->effectdata) {
1482                                                 switch(seq->type){
1483                                                 case SEQ_COLOR:
1484                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
1485                                                         break;
1486                                                 case SEQ_SPEED:
1487                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
1488                                                         break;
1489                                                 case SEQ_WIPE:
1490                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1491                                                         break;
1492                                                 case SEQ_GLOW:
1493                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1494                                                         break;
1495                                                 case SEQ_TRANSFORM:
1496                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
1497                                                         break;
1498                                                 }
1499                                         }
1500
1501                                         strip= seq->strip;
1502                                         writestruct(wd, DATA, "Strip", 1, strip);
1503                                         if(seq->flag & SEQ_USE_CROP && strip->crop) {
1504                                                 writestruct(wd, DATA, "StripCrop", 1, strip->crop);
1505                                         }
1506                                         if(seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
1507                                                 writestruct(wd, DATA, "StripTransform", 1, strip->transform);
1508                                         }
1509                                         if(seq->flag & SEQ_USE_PROXY && strip->proxy) {
1510                                                 writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
1511                                         }
1512                                         if(seq->flag & SEQ_USE_COLOR_BALANCE && strip->color_balance) {
1513                                                 writestruct(wd, DATA, "StripColorBalance", 1, strip->color_balance);
1514                                         }
1515                                         if(seq->type==SEQ_IMAGE)
1516                                                 writestruct(wd, DATA, "StripElem", MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem), strip->stripdata);
1517                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
1518                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1519
1520                                         strip->done= 1;
1521                                 }
1522                         }
1523                         END_SEQ
1524                                 
1525                         /* new; meta stack too, even when its nasty restore code */
1526                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1527                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1528                         }
1529                 }
1530
1531                 write_scriptlink(wd, &sce->scriptlink);
1532
1533                 if (sce->r.avicodecdata) {
1534                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1535                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1536                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1537                 }
1538
1539                 if (sce->r.qtcodecdata) {
1540                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1541                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1542                 }
1543                 if (sce->r.ffcodecdata.properties) {
1544                         IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
1545                 }
1546
1547                 /* writing dynamic list of TimeMarkers to the blend file */
1548                 for(marker= sce->markers.first; marker; marker= marker->next)
1549                         writestruct(wd, DATA, "TimeMarker", 1, marker);
1550                 
1551                 /* writing dynamic list of TransformOrientations to the blend file */
1552                 for(ts = sce->transform_spaces.first; ts; ts = ts->next)
1553                         writestruct(wd, DATA, "TransformOrientation", 1, ts);
1554                 
1555                 for(srl= sce->r.layers.first; srl; srl= srl->next)
1556                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
1557                 
1558                 if(sce->nodetree) {
1559                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
1560                         write_nodetree(wd, sce->nodetree);
1561                 }
1562                 
1563                 sce= sce->id.next;
1564         }
1565         /* flush helps the compression for undo-save */
1566         mywrite(wd, MYWRITE_FLUSH, 0);
1567 }
1568
1569 static void write_gpencil(WriteData *wd, bGPdata *gpd)
1570 {
1571         bGPDlayer *gpl;
1572         bGPDframe *gpf;
1573         bGPDstroke *gps;
1574         
1575         /* write gpd data block to file */
1576         writestruct(wd, DATA, "bGPdata", 1, gpd);
1577         
1578         /* write grease-pencil layers to file */
1579         for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
1580                 writestruct(wd, DATA, "bGPDlayer", 1, gpl);
1581                 
1582                 /* write this layer's frames to file */
1583                 for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
1584                         writestruct(wd, DATA, "bGPDframe", 1, gpf);
1585                         
1586                         /* write strokes */
1587                         for (gps= gpf->strokes.first; gps; gps= gps->next) {
1588                                 writestruct(wd, DATA, "bGPDstroke", 1, gps);
1589                                 writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);                               
1590                         }
1591                 }
1592         }
1593 }
1594
1595 static void write_screens(WriteData *wd, ListBase *scrbase)
1596 {
1597         bScreen *sc;
1598         ScrArea *sa;
1599         ScrVert *sv;
1600         ScrEdge *se;
1601
1602         sc= scrbase->first;
1603         while(sc) {
1604                 /* write LibData */
1605                 writestruct(wd, ID_SCR, "Screen", 1, sc);
1606                 if (sc->id.properties) IDP_WriteProperty(sc->id.properties, wd);
1607
1608                 /* direct data */
1609                 sv= sc->vertbase.first;
1610                 while(sv) {
1611                         writestruct(wd, DATA, "ScrVert", 1, sv);
1612                         sv= sv->next;
1613                 }
1614
1615                 se= sc->edgebase.first;
1616                 while(se) {
1617                         writestruct(wd, DATA, "ScrEdge", 1, se);
1618                         se= se->next;
1619                 }
1620
1621                 sa= sc->areabase.first;
1622                 while(sa) {
1623                         SpaceLink *sl;
1624                         Panel *pa;
1625
1626                         writestruct(wd, DATA, "ScrArea", 1, sa);
1627
1628                         pa= sa->panels.first;
1629                         while(pa) {
1630                                 writestruct(wd, DATA, "Panel", 1, pa);
1631                                 pa= pa->next;
1632                         }
1633
1634                         /* space handler scriptlinks */
1635                         write_scriptlink(wd, &sa->scriptlink);
1636
1637                         sl= sa->spacedata.first;
1638                         while(sl) {
1639                                 if(sl->spacetype==SPACE_VIEW3D) {
1640                                         View3D *v3d= (View3D *) sl;
1641                                         writestruct(wd, DATA, "View3D", 1, v3d);
1642                                         if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
1643                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
1644                                         if(v3d->clipbb) writestruct(wd, DATA, "BoundBox", 1, v3d->clipbb);
1645                                         if(v3d->gpd) write_gpencil(wd, v3d->gpd);
1646                                 }
1647                                 else if(sl->spacetype==SPACE_IPO) {
1648                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
1649                                 }
1650                                 else if(sl->spacetype==SPACE_BUTS) {
1651                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
1652                                 }
1653                                 else if(sl->spacetype==SPACE_FILE) {
1654                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
1655                                 }
1656                                 else if(sl->spacetype==SPACE_SEQ) {
1657                                         SpaceSeq *sseq= (SpaceSeq *)sl;
1658                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
1659                                         if(sseq->gpd) write_gpencil(wd, sseq->gpd);
1660                                 }
1661                                 else if(sl->spacetype==SPACE_OOPS) {
1662                                         SpaceOops *so= (SpaceOops *)sl;
1663                                         Oops *oops;
1664
1665                                         /* cleanup */
1666                                         oops= so->oops.first;
1667                                         while(oops) {
1668                                                 Oops *oopsn= oops->next;
1669                                                 if(oops->id==0) {
1670                                                         BLI_remlink(&so->oops, oops);
1671                                                         free_oops(oops);
1672                                                 }
1673                                                 oops= oopsn;
1674                                         }
1675
1676                                         /* ater cleanup, because of listbase! */
1677                                         writestruct(wd, DATA, "SpaceOops", 1, so);
1678
1679                                         oops= so->oops.first;
1680                                         while(oops) {
1681                                                 writestruct(wd, DATA, "Oops", 1, oops);
1682                                                 oops= oops->next;
1683                                         }
1684                                         /* outliner */
1685                                         if(so->treestore) {
1686                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
1687                                                 if(so->treestore->data)
1688                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
1689                                         }
1690                                 }
1691                                 else if(sl->spacetype==SPACE_IMAGE) {
1692                                         SpaceImage *sima= (SpaceImage *)sl;
1693                                         
1694                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
1695                                         if(sima->cumap)
1696                                                 write_curvemapping(wd, sima->cumap);                                    
1697                                 }
1698                                 else if(sl->spacetype==SPACE_IMASEL) {
1699                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
1700                                 }
1701                                 else if(sl->spacetype==SPACE_TEXT) {
1702                                         writestruct(wd, DATA, "SpaceText", 1, sl);
1703                                 }
1704                                 else if(sl->spacetype==SPACE_SCRIPT) {
1705                                         SpaceScript *sc = (SpaceScript*)sl;
1706                                         sc->but_refs = NULL;
1707                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
1708                                 }
1709                                 else if(sl->spacetype==SPACE_ACTION) {
1710                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
1711                                 }
1712                                 else if(sl->spacetype==SPACE_SOUND) {
1713                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
1714                                 }
1715                                 else if(sl->spacetype==SPACE_NLA){
1716                                         writestruct(wd, DATA, "SpaceNla", 1, sl);
1717                                 }
1718                                 else if(sl->spacetype==SPACE_TIME){
1719                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
1720                                 }
1721                                 else if(sl->spacetype==SPACE_NODE){
1722                                         SpaceNode *snode= (SpaceNode *)sl;
1723                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
1724                                         if(snode->gpd) write_gpencil(wd, snode->gpd);
1725                                 }
1726                                 sl= sl->next;
1727                         }
1728
1729                         sa= sa->next;
1730                 }
1731
1732                 sc= sc->id.next;
1733         }
1734 }
1735
1736 static void write_libraries(WriteData *wd, Main *main)
1737 {
1738         ListBase *lbarray[30];
1739         ID *id;
1740         int a, tot, foundone;
1741
1742         for(; main; main= main->next) {
1743
1744                 a=tot= set_listbasepointers(main, lbarray);
1745
1746                 /* test: is lib being used */
1747                 foundone= 0;
1748                 while(tot--) {
1749                         for(id= lbarray[tot]->first; id; id= id->next) {
1750                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
1751                                         foundone= 1;
1752                                         break;
1753                                 }
1754                         }
1755                         if(foundone) break;
1756                 }
1757
1758                 if(foundone) {
1759                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
1760
1761                         while(a--) {
1762                                 for(id= lbarray[a]->first; id; id= id->next) {
1763                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
1764                                                 writestruct(wd, ID_ID, "ID", 1, id);
1765                                         }
1766                                 }
1767                         }
1768                 }
1769         }
1770 }
1771
1772 static void write_bone(WriteData *wd, Bone* bone)
1773 {
1774         Bone*   cbone;
1775
1776         // PATCH for upward compatibility after 2.37+ armature recode
1777         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
1778                 
1779         // Write this bone
1780         writestruct(wd, DATA, "Bone", 1, bone);
1781         
1782         // Write Children
1783         cbone= bone->childbase.first;
1784         while(cbone) {
1785                 write_bone(wd, cbone);
1786                 cbone= cbone->next;
1787         }
1788 }
1789
1790 static void write_armatures(WriteData *wd, ListBase *idbase)
1791 {
1792         bArmature       *arm;
1793         Bone            *bone;
1794
1795         arm=idbase->first;
1796         while (arm) {
1797                 if (arm->id.us>0 || wd->current) {
1798                         writestruct(wd, ID_AR, "bArmature", 1, arm);
1799                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
1800
1801                         /* Direct data */
1802                         bone= arm->bonebase.first;
1803                         while(bone) {
1804                                 write_bone(wd, bone);
1805                                 bone=bone->next;
1806                         }
1807                 }
1808                 arm=arm->id.next;
1809         }
1810
1811         /* flush helps the compression for undo-save */
1812         mywrite(wd, MYWRITE_FLUSH, 0);
1813 }
1814
1815 static void write_actions(WriteData *wd, ListBase *idbase)
1816 {
1817         bAction                 *act;
1818         bActionChannel  *chan;
1819         bActionGroup    *grp;
1820         TimeMarker *marker;
1821         
1822         for(act=idbase->first; act; act= act->id.next) {
1823                 if (act->id.us>0 || wd->current) {
1824                         writestruct(wd, ID_AC, "bAction", 1, act);
1825                         if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
1826                         
1827                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1828                                 writestruct(wd, DATA, "bActionChannel", 1, chan);
1829                                 write_constraint_channels(wd, &chan->constraintChannels);
1830                         }
1831                         
1832                         for (grp=act->groups.first; grp; grp=grp->next) {
1833                                 writestruct(wd, DATA, "bActionGroup", 1, grp);
1834                         }
1835                         
1836                         for (marker=act->markers.first; marker; marker=marker->next) {
1837                                 writestruct(wd, DATA, "TimeMarker", 1, marker);
1838                         }
1839                 }
1840         }
1841 }
1842
1843 static void write_texts(WriteData *wd, ListBase *idbase)
1844 {
1845         Text *text;
1846         TextLine *tmp;
1847
1848         text= idbase->first;
1849         while(text) {
1850                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
1851
1852                 /* write LibData */
1853                 writestruct(wd, ID_TXT, "Text", 1, text);
1854                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
1855                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
1856
1857                 if(!(text->flags & TXT_ISEXT)) {
1858                         /* now write the text data, in two steps for optimization in the readfunction */
1859                         tmp= text->lines.first;
1860                         while (tmp) {
1861                                 writestruct(wd, DATA, "TextLine", 1, tmp);
1862                                 tmp= tmp->next;
1863                         }
1864
1865                         tmp= text->lines.first;
1866                         while (tmp) {
1867                                 writedata(wd, DATA, tmp->len+1, tmp->line);
1868                                 tmp= tmp->next;
1869                         }
1870                 }
1871                 text= text->id.next;
1872         }
1873
1874         /* flush helps the compression for undo-save */
1875         mywrite(wd, MYWRITE_FLUSH, 0);
1876 }
1877
1878 static void write_sounds(WriteData *wd, ListBase *idbase)
1879 {
1880         bSound *sound;
1881         bSample *sample;
1882
1883         PackedFile * pf;
1884
1885         // set all samples to unsaved status
1886
1887         sample = samples->first; // samples is a global defined in sound.c
1888         while (sample) {
1889                 sample->flags |= SAMPLE_NEEDS_SAVE;
1890                 sample = sample->id.next;
1891         }
1892
1893         sound= idbase->first;
1894         while(sound) {
1895                 if(sound->id.us>0 || wd->current) {
1896                         // do we need to save the packedfile as well ?
1897                         sample = sound->sample;
1898                         if (sample) {
1899                                 if (sample->flags & SAMPLE_NEEDS_SAVE) {
1900                                         sound->newpackedfile = sample->packedfile;
1901                                         sample->flags &= ~SAMPLE_NEEDS_SAVE;
1902                                 } else {
1903                                         sound->newpackedfile = NULL;
1904                                 }
1905                         }
1906
1907                         /* write LibData */
1908                         writestruct(wd, ID_SO, "bSound", 1, sound);
1909                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
1910
1911                         if (sound->newpackedfile) {
1912                                 pf = sound->newpackedfile;
1913                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1914                                 writedata(wd, DATA, pf->size, pf->data);
1915                         }
1916
1917                         if (sample) {
1918                                 sound->newpackedfile = sample->packedfile;
1919                         }
1920                 }
1921                 sound= sound->id.next;
1922         }
1923
1924         /* flush helps the compression for undo-save */
1925         mywrite(wd, MYWRITE_FLUSH, 0);
1926 }
1927
1928 static void write_groups(WriteData *wd, ListBase *idbase)
1929 {
1930         Group *group;
1931         GroupObject *go;
1932
1933         for(group= idbase->first; group; group= group->id.next) {
1934                 if(group->id.us>0 || wd->current) {
1935                         /* write LibData */
1936                         writestruct(wd, ID_GR, "Group", 1, group);
1937                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
1938
1939                         go= group->gobject.first;
1940                         while(go) {
1941                                 writestruct(wd, DATA, "GroupObject", 1, go);
1942                                 go= go->next;
1943                         }
1944                 }
1945         }
1946 }
1947
1948 static void write_nodetrees(WriteData *wd, ListBase *idbase)
1949 {
1950         bNodeTree *ntree;
1951         
1952         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
1953                 if (ntree->id.us>0 || wd->current) {
1954                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
1955                         write_nodetree(wd, ntree);
1956                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
1957                 }
1958         }
1959 }
1960
1961 static void write_brushes(WriteData *wd, ListBase *idbase)
1962 {
1963         Brush *brush;
1964         int a;
1965         
1966         for(brush=idbase->first; brush; brush= brush->id.next) {
1967                 if(brush->id.us>0 || wd->current) {
1968                         writestruct(wd, ID_BR, "Brush", 1, brush);
1969                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
1970                         for(a=0; a<MAX_MTEX; a++)
1971                                 if(brush->mtex[a])
1972                                         writestruct(wd, DATA, "MTex", 1, brush->mtex[a]);
1973                 }
1974         }
1975 }
1976
1977 static void write_scripts(WriteData *wd, ListBase *idbase)
1978 {
1979         Script *script;
1980         
1981         for(script=idbase->first; script; script= script->id.next) {
1982                 if(script->id.us>0 || wd->current) {
1983                         writestruct(wd, ID_SCRIPT, "Script", 1, script);
1984                         if (script->id.properties) IDP_WriteProperty(script->id.properties, wd);
1985                 }
1986         }
1987 }
1988
1989 static void write_global(WriteData *wd)
1990 {
1991         FileGlobal fg;
1992         char subvstr[8];
1993         
1994         fg.curscreen= G.curscreen;
1995         fg.curscene= G.scene;
1996         fg.displaymode= G.displaymode;
1997         fg.winpos= G.winpos;
1998         fg.fileflags= (G.fileflags & ~G_FILE_NO_UI);    // prevent to save this, is not good convention, and feature with concerns...
1999         fg.globalf= G.f;
2000
2001         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
2002         memcpy(fg.subvstr, subvstr, 4);
2003         
2004         fg.subversion= BLENDER_SUBVERSION;
2005         fg.minversion= BLENDER_MINVERSION;
2006         fg.minsubversion= BLENDER_MINSUBVERSION;
2007         
2008         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
2009 }
2010
2011 /* if MemFile * there's filesave to memory */
2012 static int write_file_handle(int handle, MemFile *compare, MemFile *current, int write_user_block, int write_flags)
2013 {
2014         BHead bhead;
2015         ListBase mainlist;
2016         char buf[16];
2017         WriteData *wd;
2018
2019         blo_split_main(&mainlist, G.main);
2020
2021         wd= bgnwrite(handle, compare, current, write_flags);
2022         
2023         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (G.order==B_ENDIAN)?'V':'v', G.version);
2024         mywrite(wd, buf, 12);
2025
2026         write_renderinfo(wd);
2027         write_global(wd);
2028
2029         if(current==NULL)
2030                 write_screens  (wd, &G.main->screen);   /* no UI save in undo */
2031         write_scenes   (wd, &G.main->scene);
2032         write_curves   (wd, &G.main->curve);
2033         write_mballs   (wd, &G.main->mball);
2034         write_images   (wd, &G.main->image);
2035         write_cameras  (wd, &G.main->camera);
2036         write_lamps    (wd, &G.main->lamp);
2037         write_lattices (wd, &G.main->latt);
2038         write_vfonts   (wd, &G.main->vfont);
2039         write_ipos     (wd, &G.main->ipo);
2040         write_keys     (wd, &G.main->key);
2041         write_worlds   (wd, &G.main->world);
2042         write_texts    (wd, &G.main->text);
2043         write_sounds   (wd, &G.main->sound);
2044         write_groups   (wd, &G.main->group);
2045         write_armatures(wd, &G.main->armature);
2046         write_actions  (wd, &G.main->action);
2047         write_objects  (wd, &G.main->object);
2048         write_materials(wd, &G.main->mat);
2049         write_textures (wd, &G.main->tex);
2050         write_meshs    (wd, &G.main->mesh);
2051         write_particlesettings(wd, &G.main->particle);
2052         write_nodetrees(wd, &G.main->nodetree);
2053         write_brushes  (wd, &G.main->brush);
2054         write_scripts  (wd, &G.main->script);
2055         if(current==NULL)       
2056                 write_libraries(wd,  G.main->next); /* no library save in undo */
2057
2058         if (write_user_block) {
2059                 write_userdef(wd);
2060         }
2061
2062         /* dna as last, because (to be implemented) test for which structs are written */
2063         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
2064
2065         /* end of file */
2066         memset(&bhead, 0, sizeof(BHead));
2067         bhead.code= ENDB;
2068         mywrite(wd, &bhead, sizeof(BHead));
2069
2070         blo_join_main(&mainlist);
2071         G.main= mainlist.first;
2072
2073         return endwrite(wd);
2074 }
2075
2076 /* return: success (1) */
2077 int BLO_write_file(char *dir, int write_flags, char **error_r)
2078 {
2079         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
2080         char tempname[FILE_MAXDIR+FILE_MAXFILE];
2081         int file, err, write_user_block;
2082
2083         sprintf(tempname, "%s@", dir);
2084
2085         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
2086         if(file == -1) {
2087                 *error_r= "Unable to open";
2088                 return 0;
2089         }
2090
2091         BLI_make_file_string(G.sce, userfilename, BLI_gethome(), ".B.blend");
2092
2093         write_user_block= BLI_streq(dir, userfilename);
2094
2095         err= write_file_handle(file, NULL,NULL, write_user_block, write_flags);
2096         close(file);
2097
2098         if(!err) {
2099                 if(write_flags & G_FILE_COMPRESS)
2100                 {       
2101                         // compressed files have the same ending as regular files... only from 2.4!!!
2102                         
2103                         int ret = BLI_gzip(tempname, dir);
2104                         
2105                         if(-1==ret) {
2106                                 *error_r= "Failed opening .gz file";
2107                                 return 0;
2108                         }
2109                         if(-2==ret) {
2110                                 *error_r= "Failed opening .blend file for compression";
2111                                 return 0;
2112                         }
2113                 }
2114                 else
2115                 if(BLI_rename(tempname, dir) != 0) {
2116                         *error_r= "Can't change old file. File saved with @";
2117                         return 0;
2118                 }
2119
2120                 
2121         } else {
2122                 *error_r= strerror(errno);
2123                 remove(tempname);
2124
2125                 return 0;
2126         }
2127
2128         return 1;
2129 }
2130
2131 /* return: success (1) */
2132 int BLO_write_file_mem(MemFile *compare, MemFile *current, int write_flags, char **error_r)
2133 {
2134         int err;
2135
2136         err= write_file_handle(0, compare, current, 0, write_flags);
2137         
2138         if(err==0) return 1;
2139         return 0;
2140 }
2141
2142
2143         /* Runtime writing */
2144
2145 #ifdef WIN32
2146 #define PATHSEPERATOR           "\\"
2147 #else
2148 #define PATHSEPERATOR           "/"
2149 #endif
2150
2151 char *get_install_dir(void) {
2152         extern char bprogname[];
2153         char *tmpname = BLI_strdup(bprogname);
2154         char *cut;
2155
2156 #ifdef __APPLE__
2157         cut = strstr(tmpname, ".app");
2158         if (cut) cut[0] = 0;
2159 #endif
2160
2161         cut = BLI_last_slash(tmpname);
2162
2163         if (cut) {
2164                 cut[0] = 0;
2165                 return tmpname;
2166         } else {
2167                 MEM_freeN(tmpname);
2168                 return NULL;
2169         }
2170 }
2171
2172 static char *get_runtime_path(char *exename) {
2173         char *installpath= get_install_dir();
2174
2175         if (!installpath) {
2176                 return NULL;
2177         } else {
2178                 char *path= MEM_mallocN(strlen(installpath)+strlen(PATHSEPERATOR)+strlen(exename)+1, "runtimepath");
2179
2180                 if (path == NULL) {
2181                         MEM_freeN(installpath);
2182                         return NULL;
2183                 }
2184
2185                 strcpy(path, installpath);
2186                 strcat(path, PATHSEPERATOR);
2187                 strcat(path, exename);
2188
2189                 MEM_freeN(installpath);
2190
2191                 return path;
2192         }
2193 }
2194
2195 #ifdef __APPLE__
2196
2197 static int recursive_copy_runtime(char *outname, char *exename, char **cause_r) 
2198 {
2199         char *cause = NULL, *runtime = get_runtime_path(exename);
2200         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
2201         int progfd = -1;
2202
2203         if (!runtime) {
2204                 cause= "Unable to find runtime";
2205                 goto cleanup;
2206         }
2207         //printf("runtimepath %s\n", runtime);
2208                 
2209         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2210         if (progfd==-1) {
2211                 cause= "Unable to find runtime";
2212                 goto cleanup;
2213         }
2214
2215         sprintf(command, "/bin/cp -R \"%s\" \"%s\"", runtime, outname);
2216         //printf("command %s\n", command);
2217         if (system(command) == -1) {
2218                 cause = "Couldn't copy runtime";
2219         }
2220
2221 cleanup:
2222         if (progfd!=-1)
2223                 close(progfd);
2224         if (runtime)
2225                 MEM_freeN(runtime);
2226
2227         if (cause) {
2228                 *cause_r= cause;
2229                 return 0;
2230         } else
2231                 return 1;
2232 }
2233
2234 void BLO_write_runtime(char *file, char *exename) {
2235         char gamename[FILE_MAXDIR+FILE_MAXFILE];
2236         int outfd = -1;
2237         char *cause= NULL;
2238
2239         // remove existing file / bundle
2240         //printf("Delete file %s\n", file);
2241         BLI_delete(file, 0, TRUE);
2242
2243         if (!recursive_copy_runtime(file, exename, &cause))
2244                 goto cleanup;
2245
2246         strcpy(gamename, file);
2247         strcat(gamename, "/Contents/Resources/game.blend");
2248         //printf("gamename %s\n", gamename);
2249         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2250         if (outfd != -1) {
2251
2252                 write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
2253
2254                 if (write(outfd, " ", 1) != 1) {
2255                         cause= "Unable to write to output file";
2256                         goto cleanup;
2257                 }
2258         } else {
2259                 cause = "Unable to open blenderfile";
2260         }
2261
2262 cleanup:
2263         if (outfd!=-1)
2264                 close(outfd);
2265
2266         if (cause)
2267                 error("Unable to make runtime: %s", cause);
2268 }
2269
2270 #else /* !__APPLE__ */
2271
2272 static int handle_append_runtime(int handle, char *exename, char **cause_r) {
2273         char *cause= NULL, *runtime= get_runtime_path(exename);
2274         unsigned char buf[1024];
2275         int count, progfd= -1;
2276
2277         if (!runtime) {
2278                 cause= "Unable to find runtime";
2279                 goto cleanup;
2280         }
2281
2282         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2283         if (progfd==-1) {
2284                 cause= "Unable to find runtime";
2285                 goto cleanup;
2286         }
2287
2288         while ((count= read(progfd, buf, sizeof(buf)))>0) {
2289                 if (write(handle, buf, count)!=count) {
2290                         cause= "Unable to write to output file";
2291                         goto cleanup;
2292                 }
2293         }
2294
2295 cleanup:
2296         if (progfd!=-1)
2297                 close(progfd);
2298         if (runtime)
2299                 MEM_freeN(runtime);
2300
2301         if (cause) {
2302                 *cause_r= cause;
2303                 return 0;
2304         } else
2305                 return 1;
2306 }
2307
2308 static int handle_write_msb_int(int handle, int i) {
2309         unsigned char buf[4];
2310         buf[0]= (i>>24)&0xFF;
2311         buf[1]= (i>>16)&0xFF;
2312         buf[2]= (i>>8)&0xFF;
2313         buf[3]= (i>>0)&0xFF;
2314
2315         return (write(handle, buf, 4)==4);
2316 }
2317
2318 void BLO_write_runtime(char *file, char *exename) {
2319         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2320         char *cause= NULL;
2321         int datastart;
2322
2323         if (!outfd) {
2324                 cause= "Unable to open output file";
2325                 goto cleanup;
2326         }
2327         if (!handle_append_runtime(outfd, exename, &cause))
2328                 goto cleanup;
2329
2330         datastart= lseek(outfd, 0, SEEK_CUR);
2331
2332         write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
2333
2334         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
2335                 cause= "Unable to write to output file";
2336                 goto cleanup;
2337         }
2338
2339 cleanup:
2340         if (outfd!=-1)
2341                 close(outfd);
2342
2343         if (cause)
2344                 error("Unable to make runtime: %s", cause);
2345 }
2346
2347 #endif /* !__APPLE__ */