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