== Constraints System ==
[blender-staging.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_CHILDOF:
716                         writestruct(wd, DATA, "bChildOfConstraint", 1, con->data);
717                         break;
718                 case CONSTRAINT_TYPE_TRACKTO:
719                         writestruct(wd, DATA, "bTrackToConstraint", 1, con->data);
720                         break;
721                 case CONSTRAINT_TYPE_KINEMATIC:
722                         writestruct(wd, DATA, "bKinematicConstraint", 1, con->data);
723                         break;
724                 case CONSTRAINT_TYPE_ROTLIKE:
725                         writestruct(wd, DATA, "bRotateLikeConstraint", 1, con->data);
726                         break;
727                 case CONSTRAINT_TYPE_LOCLIKE:
728                         writestruct(wd, DATA, "bLocateLikeConstraint", 1, con->data);
729                         break;
730                 case CONSTRAINT_TYPE_SIZELIKE:
731                         writestruct(wd, DATA, "bSizeLikeConstraint", 1, con->data);
732                         break;
733                 case CONSTRAINT_TYPE_ACTION:
734                         writestruct(wd, DATA, "bActionConstraint", 1, con->data);
735                         break;
736                 case CONSTRAINT_TYPE_LOCKTRACK:
737                         writestruct(wd, DATA, "bLockTrackConstraint", 1, con->data);
738                         break;
739                 case CONSTRAINT_TYPE_FOLLOWPATH:
740                         writestruct(wd, DATA, "bFollowPathConstraint", 1, con->data);
741                         break;
742                 case CONSTRAINT_TYPE_STRETCHTO:
743                         writestruct(wd, DATA, "bStretchToConstraint", 1, con->data);
744                         break;
745                 case CONSTRAINT_TYPE_MINMAX:
746                         writestruct(wd, DATA, "bMinMaxConstraint", 1, con->data);
747                         break;
748                 case CONSTRAINT_TYPE_LOCLIMIT:
749                         writestruct(wd, DATA, "bLocLimitConstraint", 1, con->data);
750                         break;
751                 case CONSTRAINT_TYPE_ROTLIMIT:
752                         writestruct(wd, DATA, "bRotLimitConstraint", 1, con->data);
753                         break;
754                 case CONSTRAINT_TYPE_SIZELIMIT:
755                         writestruct(wd, DATA, "bSizeLimitConstraint", 1, con->data);
756                         break;
757                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
758                         writestruct(wd, DATA, "bRigidBodyJointConstraint", 1, con->data);
759                         break;
760                 case CONSTRAINT_TYPE_CLAMPTO:
761                         writestruct(wd, DATA, "bClampToConstraint", 1, con->data);
762                         break;
763                 default:
764                         break;
765                 }
766                 /* Write the constraint */
767                 writestruct(wd, DATA, "bConstraint", 1, con);
768         }
769 }
770
771 static void write_pose(WriteData *wd, bPose *pose)
772 {
773         bPoseChannel *chan;
774
775         /* Write each channel */
776         if (!pose)
777                 return;
778
779         /* Write channels */
780         for (chan=pose->chanbase.first; chan; chan=chan->next) {
781                 write_constraints(wd, &chan->constraints);
782                 
783                 /* prevent crashes with autosave, when a bone duplicated in editmode has not yet been assigned to its posechannel */
784                 if (chan->bone) 
785                         chan->selectflag= chan->bone->flag & (BONE_SELECTED|BONE_ACTIVE); /* gets restored on read, for library armatures */
786                 
787                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
788         }
789
790         /* Write this pose */
791         writestruct(wd, DATA, "bPose", 1, pose);
792 }
793
794 static void write_defgroups(WriteData *wd, ListBase *defbase)
795 {
796         bDeformGroup    *defgroup;
797
798         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
799                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
800 }
801
802 static void write_constraint_channels(WriteData *wd, ListBase *chanbase)
803 {
804         bConstraintChannel *chan;
805
806         for (chan = chanbase->first; chan; chan=chan->next)
807                 writestruct(wd, DATA, "bConstraintChannel", 1, chan);
808
809 }
810
811 static void write_modifiers(WriteData *wd, ListBase *modbase)
812 {
813         ModifierData *md;
814
815         if (modbase == NULL) return;
816         for (md=modbase->first; md; md= md->next) {
817                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
818                 if (mti == NULL) return;
819
820                 writestruct(wd, DATA, mti->structName, 1, md);
821
822                 if (md->type==eModifierType_Hook) {
823                         HookModifierData *hmd = (HookModifierData*) md;
824
825                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
826                 }
827         }
828 }
829
830 static void write_objects(WriteData *wd, ListBase *idbase)
831 {
832         Object *ob;
833         int a;
834         
835         ob= idbase->first;
836         while(ob) {
837                 if(ob->id.us>0 || wd->current) {
838                         /* write LibData */
839 #ifdef WITH_VERSE
840                         /* pointer at vnode stored in file have to be NULL */
841                         struct VNode *vnode = (VNode*)ob->vnode;
842                         if(vnode) ob->vnode = NULL;
843 #endif
844                         writestruct(wd, ID_OB, "Object", 1, ob);
845 #ifdef WITH_VERSE
846                         if(vnode) ob->vnode = (void*)vnode;
847 #endif
848
849                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
850                           of library blocks that implement this.*/
851                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
852
853                         /* direct data */
854                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
855                         write_effects(wd, &ob->effect);
856                         write_properties(wd, &ob->prop);
857                         write_sensors(wd, &ob->sensors);
858                         write_controllers(wd, &ob->controllers);
859                         write_actuators(wd, &ob->actuators);
860                         write_scriptlink(wd, &ob->scriptlink);
861                         write_pose(wd, ob->pose);
862                         write_defgroups(wd, &ob->defbase);
863                         write_constraints(wd, &ob->constraints);
864                         write_constraint_channels(wd, &ob->constraintChannels);
865                         write_nlastrips(wd, &ob->nlastrips);
866                         
867                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
868                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
869                         if(ob->soft) {
870                                 SoftBody *sb= ob->soft;
871                                 if(sb->keys) {
872                                         writedata(wd, DATA, sizeof(void *)*sb->totkey, sb->keys);
873                                         for(a=0; a<sb->totkey; a++) {
874                                                 writestruct(wd, DATA, "SBVertex", sb->totpoint, sb->keys[a]);
875                                         }
876                                 }
877                         }
878                         writestruct(wd, DATA, "FluidsimSettings", 1, ob->fluidsimSettings); // NT
879                         
880                         write_modifiers(wd, &ob->modifiers);
881                 }
882                 ob= ob->id.next;
883         }
884
885         /* flush helps the compression for undo-save */
886         mywrite(wd, MYWRITE_FLUSH, 0);
887 }
888
889
890 static void write_vfonts(WriteData *wd, ListBase *idbase)
891 {
892         VFont *vf;
893         PackedFile * pf;
894
895         vf= idbase->first;
896         while(vf) {
897                 if(vf->id.us>0 || wd->current) {
898                         /* write LibData */
899                         writestruct(wd, ID_VF, "VFont", 1, vf);
900                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
901
902                         /* direct data */
903
904                         if (vf->packedfile) {
905                                 pf = vf->packedfile;
906                                 writestruct(wd, DATA, "PackedFile", 1, pf);
907                                 writedata(wd, DATA, pf->size, pf->data);
908                         }
909                 }
910
911                 vf= vf->id.next;
912         }
913 }
914
915 static void write_ipos(WriteData *wd, ListBase *idbase)
916 {
917         Ipo *ipo;
918         IpoCurve *icu;
919
920         ipo= idbase->first;
921         while(ipo) {
922                 if(ipo->id.us>0 || wd->current) {
923                         /* write LibData */
924                         writestruct(wd, ID_IP, "Ipo", 1, ipo);
925                         if (ipo->id.properties) IDP_WriteProperty(ipo->id.properties, wd);
926
927                         /* direct data */
928                         icu= ipo->curve.first;
929                         while(icu) {
930                                 writestruct(wd, DATA, "IpoCurve", 1, icu);
931                                 icu= icu->next;
932                         }
933
934                         icu= ipo->curve.first;
935                         while(icu) {
936                                 if(icu->bezt)  writestruct(wd, DATA, "BezTriple", icu->totvert, icu->bezt);
937                                 if(icu->bp)  writestruct(wd, DATA, "BPoint", icu->totvert, icu->bp);
938                                 if(icu->driver)  writestruct(wd, DATA, "IpoDriver", 1, icu->driver);
939                                 icu= icu->next;
940                         }
941                 }
942
943                 ipo= ipo->id.next;
944         }
945
946         /* flush helps the compression for undo-save */
947         mywrite(wd, MYWRITE_FLUSH, 0);
948 }
949
950 static void write_keys(WriteData *wd, ListBase *idbase)
951 {
952         Key *key;
953         KeyBlock *kb;
954
955         key= idbase->first;
956         while(key) {
957                 if(key->id.us>0 || wd->current) {
958                         /* write LibData */
959                         writestruct(wd, ID_KE, "Key", 1, key);
960                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
961
962                         /* direct data */
963                         kb= key->block.first;
964                         while(kb) {
965                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
966                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
967                                 kb= kb->next;
968                         }
969                 }
970
971                 key= key->id.next;
972         }
973         /* flush helps the compression for undo-save */
974         mywrite(wd, MYWRITE_FLUSH, 0);
975 }
976
977 static void write_cameras(WriteData *wd, ListBase *idbase)
978 {
979         Camera *cam;
980
981         cam= idbase->first;
982         while(cam) {
983                 if(cam->id.us>0 || wd->current) {
984                         /* write LibData */
985                         writestruct(wd, ID_CA, "Camera", 1, cam);
986                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
987
988                         /* direct data */
989                         write_scriptlink(wd, &cam->scriptlink);
990                 }
991
992                 cam= cam->id.next;
993         }
994 }
995
996 static void write_mballs(WriteData *wd, ListBase *idbase)
997 {
998         MetaBall *mb;
999         MetaElem *ml;
1000
1001         mb= idbase->first;
1002         while(mb) {
1003                 if(mb->id.us>0 || wd->current) {
1004                         /* write LibData */
1005                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
1006                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
1007
1008                         /* direct data */
1009                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
1010
1011                         ml= mb->elems.first;
1012                         while(ml) {
1013                                 writestruct(wd, DATA, "MetaElem", 1, ml);
1014                                 ml= ml->next;
1015                         }
1016                 }
1017                 mb= mb->id.next;
1018         }
1019 }
1020
1021 int amount_of_chars(char *str)
1022 {
1023         // Since the data is saved as UTF-8 to the cu->str
1024         // The cu->len is not same as the strlen(cu->str)
1025         return strlen(str);
1026 }
1027
1028 static void write_curves(WriteData *wd, ListBase *idbase)
1029 {
1030         Curve *cu;
1031         Nurb *nu;
1032
1033         cu= idbase->first;
1034         while(cu) {
1035                 if(cu->id.us>0 || wd->current) {
1036                         /* write LibData */
1037                         writestruct(wd, ID_CU, "Curve", 1, cu);
1038
1039                         /* direct data */
1040                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
1041                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
1042
1043                         if(cu->vfont) {
1044                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1045                                 writestruct(wd, DATA, "CharInfo", cu->len, cu->strinfo);
1046                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);                           
1047                         }
1048                         else {
1049                                 /* is also the order of reading */
1050                                 nu= cu->nurb.first;
1051                                 while(nu) {
1052                                         writestruct(wd, DATA, "Nurb", 1, nu);
1053                                         nu= nu->next;
1054                                 }
1055                                 nu= cu->nurb.first;
1056                                 while(nu) {
1057                                         if( (nu->type & 7)==CU_BEZIER)
1058                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1059                                         else {
1060                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1061                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1062                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1063                                         }
1064                                         nu= nu->next;
1065                                 }
1066                         }
1067                 }
1068                 cu= cu->id.next;
1069         }
1070
1071         /* flush helps the compression for undo-save */
1072         mywrite(wd, MYWRITE_FLUSH, 0);
1073 }
1074
1075 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1076 {
1077         if (dvlist) {
1078                 int     i;
1079                 
1080                 /* Write the dvert list */
1081                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1082                 
1083                 /* Write deformation data for each dvert */
1084                 for (i=0; i<count; i++) {
1085                         if (dvlist[i].dw)
1086                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1087                 }
1088         }
1089 }
1090
1091 static void write_customdata(WriteData *wd, int count, CustomData *data, int partial_type, int partial_count)
1092 {
1093         int i;
1094
1095         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1096
1097         for (i=0; i<data->totlayer; i++) {
1098                 CustomDataLayer *layer= &data->layers[i];
1099                 char *structname;
1100                 int structnum, datasize;
1101
1102                 if (layer->type == CD_MDEFORMVERT) {
1103                         /* layer types that allocate own memory need special handling */
1104                         write_dverts(wd, count, layer->data);
1105                 }
1106                 else {
1107                         CustomData_file_write_info(layer->type, &structname, &structnum);
1108                         if (structnum) {
1109                                 /* when using partial visibility, the MEdge and MFace layers
1110                                    are smaller than the original, so their type and count is
1111                                    passed to make this work */
1112                                 if (layer->type != partial_type) datasize= structnum*count;
1113                                 else datasize= structnum*partial_count;
1114
1115                                 writestruct(wd, DATA, structname, datasize, layer->data);
1116                         }
1117                         else
1118                                 printf("error: this CustomDataLayer must not be written to file\n");
1119                 }
1120         }
1121 }
1122
1123 static void write_meshs(WriteData *wd, ListBase *idbase)
1124 {
1125         Mesh *mesh;
1126         MultiresLevel *lvl;
1127
1128         mesh= idbase->first;
1129         while(mesh) {
1130                 if(mesh->id.us>0 || wd->current) {
1131                         /* write LibData */
1132 #ifdef WITH_VERSE
1133                         struct VNode *vnode = (VNode*)mesh->vnode;
1134                         if(vnode) {
1135                                 /* mesh has to be created from verse geometry node*/
1136                                 create_meshdata_from_geom_node(mesh, vnode);
1137                                 /* pointer at verse node can't be stored in file */
1138                                 mesh->vnode = NULL;
1139                         }
1140 #endif
1141
1142                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
1143 #ifdef WITH_VERSE
1144                         if(vnode) mesh->vnode = (void*)vnode;
1145 #endif
1146
1147                         /* direct data */
1148                         if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1149
1150                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1151
1152                         if(mesh->pv) {
1153                                 write_customdata(wd, mesh->pv->totvert, &mesh->vdata, -1, 0);
1154                                 write_customdata(wd, mesh->pv->totedge, &mesh->edata,
1155                                         CD_MEDGE, mesh->totedge);
1156                                 write_customdata(wd, mesh->pv->totface, &mesh->fdata,
1157                                         CD_MFACE, mesh->totface);
1158                         }
1159                         else {
1160                                 write_customdata(wd, mesh->totvert, &mesh->vdata, -1, 0);
1161                                 write_customdata(wd, mesh->totedge, &mesh->edata, -1, 0);
1162                                 write_customdata(wd, mesh->totface, &mesh->fdata, -1, 0);
1163                         }
1164
1165                         /* Multires data */
1166                         writestruct(wd, DATA, "Multires", 1, mesh->mr);
1167                         if(mesh->mr) {
1168                                 lvl= mesh->mr->levels.first;
1169                                 if(lvl) {
1170                                         write_customdata(wd, lvl->totvert, &mesh->mr->vdata, -1, 0);
1171                                         write_customdata(wd, lvl->totface, &mesh->mr->fdata, -1, 0);
1172                                         writedata(wd, DATA, sizeof(short)*lvl->totedge, mesh->mr->edge_flags);
1173                                         writedata(wd, DATA, sizeof(char)*lvl->totedge, mesh->mr->edge_creases);
1174                                 }
1175
1176                                 for(; lvl; lvl= lvl->next) {
1177                                         writestruct(wd, DATA, "MultiresLevel", 1, lvl);
1178                                         writestruct(wd, DATA, "MultiresFace", lvl->totface, lvl->faces);
1179                                         writestruct(wd, DATA, "MultiresEdge", lvl->totedge, lvl->edges);
1180                                         writestruct(wd, DATA, "MultiresColFace", lvl->totface, lvl->colfaces);
1181                                 }
1182
1183                                 lvl= mesh->mr->levels.last;
1184                                 if(lvl)
1185                                         writestruct(wd, DATA, "MVert", lvl->totvert, mesh->mr->verts);
1186                         }
1187
1188                         /* PMV data */
1189                         if(mesh->pv) {
1190                                 writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
1191                                 writedata(wd, DATA, sizeof(unsigned int)*mesh->pv->totvert, mesh->pv->vert_map);
1192                                 writedata(wd, DATA, sizeof(int)*mesh->pv->totedge, mesh->pv->edge_map);
1193                                 writestruct(wd, DATA, "MFace", mesh->pv->totface, mesh->pv->old_faces);
1194                                 writestruct(wd, DATA, "MEdge", mesh->pv->totedge, mesh->pv->old_edges);
1195                         }
1196                 }
1197                 mesh= mesh->id.next;
1198         }
1199 }
1200
1201 static void write_lattices(WriteData *wd, ListBase *idbase)
1202 {
1203         Lattice *lt;
1204         
1205         lt= idbase->first;
1206         while(lt) {
1207                 if(lt->id.us>0 || wd->current) {
1208                         /* write LibData */
1209                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1210                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1211
1212                         /* direct data */
1213                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1214                         
1215                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1216                         
1217                 }
1218                 lt= lt->id.next;
1219         }
1220 }
1221
1222 static void write_images(WriteData *wd, ListBase *idbase)
1223 {
1224         Image *ima;
1225         PackedFile * pf;
1226         PreviewImage *prv;
1227
1228         ima= idbase->first;
1229         while(ima) {
1230                 if(ima->id.us>0 || wd->current) {
1231                         /* write LibData */
1232                         writestruct(wd, ID_IM, "Image", 1, ima);
1233                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1234
1235                         if (ima->packedfile) {
1236                                 pf = ima->packedfile;
1237                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1238                                 writedata(wd, DATA, pf->size, pf->data);
1239                         }
1240
1241                         if (ima->preview) {
1242                                 prv = ima->preview;
1243                                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1244                                 writedata(wd, DATA, prv->w*prv->h*sizeof(unsigned int), prv->rect);
1245                         }
1246                 }
1247                 ima= ima->id.next;
1248         }
1249         /* flush helps the compression for undo-save */
1250         mywrite(wd, MYWRITE_FLUSH, 0);
1251 }
1252
1253 static void write_textures(WriteData *wd, ListBase *idbase)
1254 {
1255         Tex *tex;
1256
1257         tex= idbase->first;
1258         while(tex) {
1259                 if(tex->id.us>0 || wd->current) {
1260                         /* write LibData */
1261                         writestruct(wd, ID_TE, "Tex", 1, tex);
1262                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1263
1264                         /* direct data */
1265                         if(tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1266                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1267                         if(tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1268                 }
1269                 tex= tex->id.next;
1270         }
1271
1272         /* flush helps the compression for undo-save */
1273         mywrite(wd, MYWRITE_FLUSH, 0);
1274 }
1275
1276 static void write_materials(WriteData *wd, ListBase *idbase)
1277 {
1278         Material *ma;
1279         int a;
1280
1281         ma= idbase->first;
1282         while(ma) {
1283                 if(ma->id.us>0 || wd->current) {
1284                         /* write LibData */
1285                         writestruct(wd, ID_MA, "Material", 1, ma);
1286                         
1287                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1288                           of library blocks that implement this.*/
1289                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1290                           set yet :) */
1291                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1292
1293                         for(a=0; a<MAX_MTEX; a++) {
1294                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1295                         }
1296                         
1297                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1298                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1299                         
1300                         write_scriptlink(wd, &ma->scriptlink);
1301                         
1302                         /* nodetree is integral part of material, no libdata */
1303                         if(ma->nodetree) {
1304                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1305                                 write_nodetree(wd, ma->nodetree);
1306                         }
1307                 }
1308                 ma= ma->id.next;
1309         }
1310 }
1311
1312 static void write_worlds(WriteData *wd, ListBase *idbase)
1313 {
1314         World *wrld;
1315         int a;
1316
1317         wrld= idbase->first;
1318         while(wrld) {
1319                 if(wrld->id.us>0 || wd->current) {
1320                         /* write LibData */
1321                         writestruct(wd, ID_WO, "World", 1, wrld);
1322                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1323
1324                         for(a=0; a<MAX_MTEX; a++) {
1325                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1326                         }
1327
1328                         write_scriptlink(wd, &wrld->scriptlink);
1329                 }
1330                 wrld= wrld->id.next;
1331         }
1332 }
1333
1334 static void write_lamps(WriteData *wd, ListBase *idbase)
1335 {
1336         Lamp *la;
1337         int a;
1338
1339         la= idbase->first;
1340         while(la) {
1341                 if(la->id.us>0 || wd->current) {
1342                         /* write LibData */
1343                         writestruct(wd, ID_LA, "Lamp", 1, la);
1344                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1345
1346                         /* direct data */
1347                         for(a=0; a<MAX_MTEX; a++) {
1348                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1349                         }
1350
1351                         write_scriptlink(wd, &la->scriptlink);
1352                 }
1353                 la= la->id.next;
1354         }
1355 }
1356
1357
1358 static void write_scenes(WriteData *wd, ListBase *scebase)
1359 {
1360         Scene *sce;
1361         Base *base;
1362         Editing *ed;
1363         Sequence *seq;
1364         MetaStack *ms;
1365         Strip *strip;
1366         TimeMarker *marker;
1367         SceneRenderLayer *srl;
1368         int a;
1369         
1370         sce= scebase->first;
1371         while(sce) {
1372                 /* write LibData */
1373                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1374                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1375
1376                 /* direct data */
1377                 base= sce->base.first;
1378                 while(base) {
1379                         writestruct(wd, DATA, "Base", 1, base);
1380                         base= base->next;
1381                 }
1382
1383                 writestruct(wd, DATA, "Radio", 1, sce->radio);
1384                 writestruct(wd, DATA, "ToolSettings", 1, sce->toolsettings);
1385
1386                 for(a=0; a<MAX_MTEX; ++a)
1387                         writestruct(wd, DATA, "MTex", 1, sce->sculptdata.mtex[a]);
1388
1389                 ed= sce->ed;
1390                 if(ed) {
1391                         writestruct(wd, DATA, "Editing", 1, ed);
1392
1393                         /* reset write flags too */
1394                         WHILE_SEQ(&ed->seqbase) {
1395                                 if(seq->strip) seq->strip->done= 0;
1396                                 writestruct(wd, DATA, "Sequence", 1, seq);
1397                         }
1398                         END_SEQ
1399
1400                         WHILE_SEQ(&ed->seqbase) {
1401                                 if(seq->strip && seq->strip->done==0) {
1402                                         /* write strip with 'done' at 0 because readfile */
1403
1404                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1405                                         if(seq->effectdata) {
1406                                                 switch(seq->type){
1407                                                 case SEQ_COLOR:
1408                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
1409                                                         break;
1410                                                 case SEQ_SPEED:
1411                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
1412                                                         break;
1413                                                 case SEQ_WIPE:
1414                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1415                                                         break;
1416                                                 case SEQ_GLOW:
1417                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1418                                                         break;
1419                                                 case SEQ_TRANSFORM:
1420                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
1421                                                         break;
1422                                                 }
1423                                         }
1424
1425                                         strip= seq->strip;
1426                                         writestruct(wd, DATA, "Strip", 1, strip);
1427
1428                                         if(seq->type==SEQ_IMAGE)
1429                                                 writestruct(wd, DATA, "StripElem", strip->len, strip->stripdata);
1430                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
1431                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1432
1433                                         strip->done= 1;
1434                                 }
1435                         }
1436                         END_SEQ
1437                                 
1438                         /* new; meta stack too, even when its nasty restore code */
1439                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1440                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1441                         }
1442                 }
1443
1444                 write_scriptlink(wd, &sce->scriptlink);
1445
1446                 if (sce->r.avicodecdata) {
1447                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1448                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1449                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1450                 }
1451
1452                 if (sce->r.qtcodecdata) {
1453                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1454                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1455                 }
1456
1457                 /* writing dynamic list of TimeMarkers to the blend file */
1458                 for(marker= sce->markers.first; marker; marker= marker->next)
1459                         writestruct(wd, DATA, "TimeMarker", 1, marker);
1460                 
1461                 for(srl= sce->r.layers.first; srl; srl= srl->next)
1462                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
1463                 
1464                 if(sce->nodetree) {
1465                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
1466                         write_nodetree(wd, sce->nodetree);
1467                 }
1468                 
1469                 sce= sce->id.next;
1470         }
1471         /* flush helps the compression for undo-save */
1472         mywrite(wd, MYWRITE_FLUSH, 0);
1473 }
1474
1475 static void write_screens(WriteData *wd, ListBase *scrbase)
1476 {
1477         bScreen *sc;
1478         ScrArea *sa;
1479         ScrVert *sv;
1480         ScrEdge *se;
1481
1482         sc= scrbase->first;
1483         while(sc) {
1484                 /* write LibData */
1485                 writestruct(wd, ID_SCR, "Screen", 1, sc);
1486                 if (sc->id.properties) IDP_WriteProperty(sc->id.properties, wd);
1487
1488                 /* direct data */
1489                 sv= sc->vertbase.first;
1490                 while(sv) {
1491                         writestruct(wd, DATA, "ScrVert", 1, sv);
1492                         sv= sv->next;
1493                 }
1494
1495                 se= sc->edgebase.first;
1496                 while(se) {
1497                         writestruct(wd, DATA, "ScrEdge", 1, se);
1498                         se= se->next;
1499                 }
1500
1501                 sa= sc->areabase.first;
1502                 while(sa) {
1503                         SpaceLink *sl;
1504                         Panel *pa;
1505
1506                         writestruct(wd, DATA, "ScrArea", 1, sa);
1507
1508                         pa= sa->panels.first;
1509                         while(pa) {
1510                                 writestruct(wd, DATA, "Panel", 1, pa);
1511                                 pa= pa->next;
1512                         }
1513
1514                         /* space handler scriptlinks */
1515                         write_scriptlink(wd, &sa->scriptlink);
1516
1517                         sl= sa->spacedata.first;
1518                         while(sl) {
1519                                 if(sl->spacetype==SPACE_VIEW3D) {
1520                                         View3D *v3d= (View3D*) sl;
1521                                         writestruct(wd, DATA, "View3D", 1, v3d);
1522                                         if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
1523                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
1524                                         if(v3d->clipbb) writestruct(wd, DATA, "BoundBox", 1, v3d->clipbb);
1525                                 }
1526                                 else if(sl->spacetype==SPACE_IPO) {
1527                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
1528                                 }
1529                                 else if(sl->spacetype==SPACE_BUTS) {
1530                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
1531                                 }
1532                                 else if(sl->spacetype==SPACE_FILE) {
1533                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
1534                                 }
1535                                 else if(sl->spacetype==SPACE_SEQ) {
1536                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
1537                                 }
1538                                 else if(sl->spacetype==SPACE_OOPS) {
1539                                         SpaceOops *so= (SpaceOops *)sl;
1540                                         Oops *oops;
1541
1542                                         /* cleanup */
1543                                         oops= so->oops.first;
1544                                         while(oops) {
1545                                                 Oops *oopsn= oops->next;
1546                                                 if(oops->id==0) {
1547                                                         BLI_remlink(&so->oops, oops);
1548                                                         free_oops(oops);
1549                                                 }
1550                                                 oops= oopsn;
1551                                         }
1552
1553                                         /* ater cleanup, because of listbase! */
1554                                         writestruct(wd, DATA, "SpaceOops", 1, so);
1555
1556                                         oops= so->oops.first;
1557                                         while(oops) {
1558                                                 writestruct(wd, DATA, "Oops", 1, oops);
1559                                                 oops= oops->next;
1560                                         }
1561                                         /* outliner */
1562                                         if(so->treestore) {
1563                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
1564                                                 if(so->treestore->data)
1565                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
1566                                         }
1567                                 }
1568                                 else if(sl->spacetype==SPACE_IMAGE) {
1569                                         SpaceImage *sima= (SpaceImage *)sl;
1570                                         
1571                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
1572                                         if(sima->cumap)
1573                                                 write_curvemapping(wd, sima->cumap);                                    
1574                                 }
1575                                 else if(sl->spacetype==SPACE_IMASEL) {
1576                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
1577                                 }
1578                                 else if(sl->spacetype==SPACE_TEXT) {
1579                                         writestruct(wd, DATA, "SpaceText", 1, sl);
1580                                 }
1581                                 else if(sl->spacetype==SPACE_SCRIPT) {
1582                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
1583                                 }
1584                                 else if(sl->spacetype==SPACE_ACTION) {
1585                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
1586                                 }
1587                                 else if(sl->spacetype==SPACE_SOUND) {
1588                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
1589                                 }
1590                                 else if(sl->spacetype==SPACE_NLA){
1591                                         writestruct(wd, DATA, "SpaceNla", 1, sl);
1592                                 }
1593                                 else if(sl->spacetype==SPACE_TIME){
1594                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
1595                                 }
1596                                 else if(sl->spacetype==SPACE_NODE){
1597                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
1598                                 }
1599                                 sl= sl->next;
1600                         }
1601
1602                         sa= sa->next;
1603                 }
1604
1605                 sc= sc->id.next;
1606         }
1607 }
1608
1609 static void write_libraries(WriteData *wd, Main *main)
1610 {
1611         ListBase *lbarray[30];
1612         ID *id;
1613         int a, tot, foundone;
1614
1615         for(; main; main= main->next) {
1616
1617                 a=tot= set_listbasepointers(main, lbarray);
1618
1619                 /* test: is lib being used */
1620                 foundone= 0;
1621                 while(tot--) {
1622                         for(id= lbarray[tot]->first; id; id= id->next) {
1623                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
1624                                         foundone= 1;
1625                                         break;
1626                                 }
1627                         }
1628                         if(foundone) break;
1629                 }
1630
1631                 if(foundone) {
1632                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
1633
1634                         while(a--) {
1635                                 for(id= lbarray[a]->first; id; id= id->next) {
1636                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
1637                                                 writestruct(wd, ID_ID, "ID", 1, id);
1638                                         }
1639                                 }
1640                         }
1641                 }
1642         }
1643 }
1644
1645 static void write_bone(WriteData *wd, Bone* bone)
1646 {
1647         Bone*   cbone;
1648
1649         // PATCH for upward compatibility after 2.37+ armature recode
1650         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
1651                 
1652         // Write this bone
1653         writestruct(wd, DATA, "Bone", 1, bone);
1654         
1655         // Write Children
1656         cbone= bone->childbase.first;
1657         while(cbone) {
1658                 write_bone(wd, cbone);
1659                 cbone= cbone->next;
1660         }
1661 }
1662
1663 static void write_armatures(WriteData *wd, ListBase *idbase)
1664 {
1665         bArmature       *arm;
1666         Bone            *bone;
1667
1668         arm=idbase->first;
1669         while (arm) {
1670                 if (arm->id.us>0 || wd->current) {
1671                         writestruct(wd, ID_AR, "bArmature", 1, arm);
1672                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
1673
1674                         /* Direct data */
1675                         bone= arm->bonebase.first;
1676                         while(bone) {
1677                                 write_bone(wd, bone);
1678                                 bone=bone->next;
1679                         }
1680                 }
1681                 arm=arm->id.next;
1682         }
1683
1684         /* flush helps the compression for undo-save */
1685         mywrite(wd, MYWRITE_FLUSH, 0);
1686 }
1687
1688 static void write_actions(WriteData *wd, ListBase *idbase)
1689 {
1690         bAction                 *act;
1691         bActionChannel  *chan;
1692         
1693         for(act=idbase->first; act; act= act->id.next) {
1694                 if (act->id.us>0 || wd->current) {
1695                         writestruct(wd, ID_AC, "bAction", 1, act);
1696                         if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
1697
1698                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1699                                 writestruct(wd, DATA, "bActionChannel", 1, chan);
1700                                 write_constraint_channels(wd, &chan->constraintChannels);
1701                         }
1702                 }
1703         }
1704 }
1705
1706 static void write_texts(WriteData *wd, ListBase *idbase)
1707 {
1708         Text *text;
1709         TextLine *tmp;
1710
1711         text= idbase->first;
1712         while(text) {
1713                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
1714
1715                 /* write LibData */
1716                 writestruct(wd, ID_TXT, "Text", 1, text);
1717                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
1718                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
1719
1720                 if(!(text->flags & TXT_ISEXT)) {
1721                         /* now write the text data, in two steps for optimization in the readfunction */
1722                         tmp= text->lines.first;
1723                         while (tmp) {
1724                                 writestruct(wd, DATA, "TextLine", 1, tmp);
1725                                 tmp= tmp->next;
1726                         }
1727
1728                         tmp= text->lines.first;
1729                         while (tmp) {
1730                                 writedata(wd, DATA, tmp->len+1, tmp->line);
1731                                 tmp= tmp->next;
1732                         }
1733                 }
1734                 text= text->id.next;
1735         }
1736
1737         /* flush helps the compression for undo-save */
1738         mywrite(wd, MYWRITE_FLUSH, 0);
1739 }
1740
1741 static void write_sounds(WriteData *wd, ListBase *idbase)
1742 {
1743         bSound *sound;
1744         bSample *sample;
1745
1746         PackedFile * pf;
1747
1748         // set all samples to unsaved status
1749
1750         sample = samples->first;
1751         while (sample) {
1752                 sample->flags |= SAMPLE_NEEDS_SAVE;
1753                 sample = sample->id.next;
1754         }
1755
1756         sound= idbase->first;
1757         while(sound) {
1758                 if(sound->id.us>0 || wd->current) {
1759                         // do we need to save the packedfile as well ?
1760                         sample = sound->sample;
1761                         if (sample) {
1762                                 if (sample->flags & SAMPLE_NEEDS_SAVE) {
1763                                         sound->newpackedfile = sample->packedfile;
1764                                         sample->flags &= ~SAMPLE_NEEDS_SAVE;
1765                                 } else {
1766                                         sound->newpackedfile = NULL;
1767                                 }
1768                         }
1769
1770                         /* write LibData */
1771                         writestruct(wd, ID_SO, "bSound", 1, sound);
1772                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
1773
1774                         if (sound->newpackedfile) {
1775                                 pf = sound->newpackedfile;
1776                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1777                                 writedata(wd, DATA, pf->size, pf->data);
1778                         }
1779
1780                         if (sample) {
1781                                 sound->newpackedfile = sample->packedfile;
1782                         }
1783                 }
1784                 sound= sound->id.next;
1785         }
1786
1787         /* flush helps the compression for undo-save */
1788         mywrite(wd, MYWRITE_FLUSH, 0);
1789 }
1790
1791 static void write_groups(WriteData *wd, ListBase *idbase)
1792 {
1793         Group *group;
1794         GroupObject *go;
1795
1796         for(group= idbase->first; group; group= group->id.next) {
1797                 if(group->id.us>0 || wd->current) {
1798                         /* write LibData */
1799                         writestruct(wd, ID_GR, "Group", 1, group);
1800                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
1801
1802                         go= group->gobject.first;
1803                         while(go) {
1804                                 writestruct(wd, DATA, "GroupObject", 1, go);
1805                                 go= go->next;
1806                         }
1807                 }
1808         }
1809 }
1810
1811 static void write_nodetrees(WriteData *wd, ListBase *idbase)
1812 {
1813         bNodeTree *ntree;
1814         
1815         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
1816                 if (ntree->id.us>0 || wd->current) {
1817                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
1818                         write_nodetree(wd, ntree);
1819                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
1820                 }
1821         }
1822 }
1823
1824 static void write_brushes(WriteData *wd, ListBase *idbase)
1825 {
1826         Brush *brush;
1827         int a;
1828         
1829         for(brush=idbase->first; brush; brush= brush->id.next) {
1830                 if(brush->id.us>0 || wd->current) {
1831                         writestruct(wd, ID_BR, "Brush", 1, brush);
1832                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
1833                         for(a=0; a<MAX_MTEX; a++)
1834                                 if(brush->mtex[a])
1835                                         writestruct(wd, DATA, "MTex", 1, brush->mtex[a]);
1836                 }
1837         }
1838 }
1839
1840 static void write_global(WriteData *wd)
1841 {
1842         FileGlobal fg;
1843         char subvstr[8];
1844         
1845         fg.curscreen= G.curscreen;
1846         fg.curscene= G.scene;
1847         fg.displaymode= G.displaymode;
1848         fg.winpos= G.winpos;
1849         fg.fileflags= (G.fileflags & ~G_FILE_NO_UI);    // prevent to save this, is not good convention, and feature with concerns...
1850         fg.globalf= G.f;
1851
1852         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
1853         memcpy(fg.subvstr, subvstr, 4);
1854         
1855         fg.subversion= BLENDER_SUBVERSION;
1856         fg.minversion= BLENDER_MINVERSION;
1857         fg.minsubversion= BLENDER_MINSUBVERSION;
1858         
1859         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
1860 }
1861
1862 /* if MemFile * there's filesave to memory */
1863 static int write_file_handle(int handle, MemFile *compare, MemFile *current, int write_user_block, int write_flags)
1864 {
1865         BHead bhead;
1866         ListBase mainlist;
1867         char buf[16];
1868         WriteData *wd;
1869
1870         blo_split_main(&mainlist, G.main);
1871
1872         wd= bgnwrite(handle, compare, current, write_flags);
1873         
1874         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (G.order==B_ENDIAN)?'V':'v', G.version);
1875         mywrite(wd, buf, 12);
1876
1877         write_renderinfo(wd);
1878         write_global(wd);
1879
1880         if(current==NULL)
1881                 write_screens  (wd, &G.main->screen);   /* no UI save in undo */
1882         write_scenes   (wd, &G.main->scene);
1883         write_curves   (wd, &G.main->curve);
1884         write_mballs   (wd, &G.main->mball);
1885         write_images   (wd, &G.main->image);
1886         write_cameras  (wd, &G.main->camera);
1887         write_lamps    (wd, &G.main->lamp);
1888         write_lattices (wd, &G.main->latt);
1889         write_vfonts   (wd, &G.main->vfont);
1890         write_ipos     (wd, &G.main->ipo);
1891         write_keys     (wd, &G.main->key);
1892         write_worlds   (wd, &G.main->world);
1893         write_texts    (wd, &G.main->text);
1894         write_sounds   (wd, &G.main->sound);
1895         write_groups   (wd, &G.main->group);
1896         write_armatures(wd, &G.main->armature);
1897         write_actions  (wd, &G.main->action);
1898         write_objects  (wd, &G.main->object);
1899         write_materials(wd, &G.main->mat);
1900         write_textures (wd, &G.main->tex);
1901         write_meshs    (wd, &G.main->mesh);
1902         write_nodetrees(wd, &G.main->nodetree);
1903         write_brushes  (wd, &G.main->brush);
1904         if(current==NULL)       
1905                 write_libraries(wd,  G.main->next); /* no library save in undo */
1906
1907         if (write_user_block) {
1908                 write_userdef(wd);
1909         }
1910
1911         /* dna as last, because (to be implemented) test for which structs are written */
1912         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
1913
1914         /* end of file */
1915         memset(&bhead, 0, sizeof(BHead));
1916         bhead.code= ENDB;
1917         mywrite(wd, &bhead, sizeof(BHead));
1918
1919         blo_join_main(&mainlist);
1920         G.main= mainlist.first;
1921
1922         return endwrite(wd);
1923 }
1924
1925 /* return: success (1) */
1926 int BLO_write_file(char *dir, int write_flags, char **error_r)
1927 {
1928         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
1929         char tempname[FILE_MAXDIR+FILE_MAXFILE];
1930         int file, err, write_user_block;
1931
1932         sprintf(tempname, "%s@", dir);
1933
1934         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
1935         if(file == -1) {
1936                 *error_r= "Unable to open";
1937                 return 0;
1938         }
1939
1940         BLI_make_file_string(G.sce, userfilename, BLI_gethome(), ".B.blend");
1941
1942         write_user_block= BLI_streq(dir, userfilename);
1943
1944         err= write_file_handle(file, NULL,NULL, write_user_block, write_flags);
1945         close(file);
1946
1947         if(!err) {
1948                 if(write_flags & G_FILE_COMPRESS)
1949                 {       
1950                         // compressed files have the same ending as regular files... only from 2.4!!!
1951                         
1952                         int ret = BLI_gzip(tempname, dir);
1953                         
1954                         if(-1==ret) {
1955                                 *error_r= "Failed opening .gz file";
1956                                 return 0;
1957                         }
1958                         if(-2==ret) {
1959                                 *error_r= "Failed opening .blend file for compression";
1960                                 return 0;
1961                         }
1962                 }
1963                 else
1964                 if(BLI_rename(tempname, dir) < 0) {
1965                         *error_r= "Can't change old file. File saved with @";
1966                         return 0;
1967                 }
1968
1969                 
1970         } else {
1971                 *error_r= strerror(errno);
1972                 remove(tempname);
1973
1974                 return 0;
1975         }
1976
1977         return 1;
1978 }
1979
1980 /* return: success (1) */
1981 int BLO_write_file_mem(MemFile *compare, MemFile *current, int write_flags, char **error_r)
1982 {
1983         int err;
1984
1985         err= write_file_handle(0, compare, current, 0, write_flags);
1986         
1987         if(err==0) return 1;
1988         return 0;
1989 }
1990
1991
1992         /* Runtime writing */
1993
1994 #ifdef WIN32
1995 #define PATHSEPERATOR           "\\"
1996 #else
1997 #define PATHSEPERATOR           "/"
1998 #endif
1999
2000 static char *get_install_dir(void) {
2001         extern char bprogname[];
2002         char *tmpname = BLI_strdup(bprogname);
2003         char *cut;
2004
2005 #ifdef __APPLE__
2006         cut = strstr(tmpname, ".app");
2007         if (cut) cut[0] = 0;
2008 #endif
2009
2010         cut = BLI_last_slash(tmpname);
2011
2012         if (cut) {
2013                 cut[0] = 0;
2014                 return tmpname;
2015         } else {
2016                 MEM_freeN(tmpname);
2017                 return NULL;
2018         }
2019 }
2020
2021 static char *get_runtime_path(char *exename) {
2022         char *installpath= get_install_dir();
2023
2024         if (!installpath) {
2025                 return NULL;
2026         } else {
2027                 char *path= MEM_mallocN(strlen(installpath)+strlen(PATHSEPERATOR)+strlen(exename)+1, "runtimepath");
2028
2029                 if (path == NULL) {
2030                         MEM_freeN(installpath);
2031                         return NULL;
2032                 }
2033
2034                 strcpy(path, installpath);
2035                 strcat(path, PATHSEPERATOR);
2036                 strcat(path, exename);
2037
2038                 MEM_freeN(installpath);
2039
2040                 return path;
2041         }
2042 }
2043
2044 #ifdef __APPLE__
2045
2046 static int recursive_copy_runtime(char *outname, char *exename, char **cause_r) 
2047 {
2048         char *cause = NULL, *runtime = get_runtime_path(exename);
2049         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
2050         int progfd = -1;
2051
2052         if (!runtime) {
2053                 cause= "Unable to find runtime";
2054                 goto cleanup;
2055         }
2056         //printf("runtimepath %s\n", runtime);
2057                 
2058         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2059         if (progfd==-1) {
2060                 cause= "Unable to find runtime";
2061                 goto cleanup;
2062         }
2063
2064         sprintf(command, "/bin/cp -R \"%s\" \"%s\"", runtime, outname);
2065         //printf("command %s\n", command);
2066         if (system(command) == -1) {
2067                 cause = "Couldn't copy runtime";
2068         }
2069
2070 cleanup:
2071         if (progfd!=-1)
2072                 close(progfd);
2073         if (runtime)
2074                 MEM_freeN(runtime);
2075
2076         if (cause) {
2077                 *cause_r= cause;
2078                 return 0;
2079         } else
2080                 return 1;
2081 }
2082
2083 void BLO_write_runtime(char *file, char *exename) {
2084         char gamename[FILE_MAXDIR+FILE_MAXFILE];
2085         int outfd = -1;
2086         char *cause= NULL;
2087
2088         // remove existing file / bundle
2089         //printf("Delete file %s\n", file);
2090         BLI_delete(file, 0, TRUE);
2091
2092         if (!recursive_copy_runtime(file, exename, &cause))
2093                 goto cleanup;
2094
2095         strcpy(gamename, file);
2096         strcat(gamename, "/Contents/Resources/game.blend");
2097         //printf("gamename %s\n", gamename);
2098         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2099         if (outfd != -1) {
2100
2101                 write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
2102
2103                 if (write(outfd, " ", 1) != 1) {
2104                         cause= "Unable to write to output file";
2105                         goto cleanup;
2106                 }
2107         } else {
2108                 cause = "Unable to open blenderfile";
2109         }
2110
2111 cleanup:
2112         if (outfd!=-1)
2113                 close(outfd);
2114
2115         if (cause)
2116                 error("Unable to make runtime: %s", cause);
2117 }
2118
2119 #else /* !__APPLE__ */
2120
2121 static int handle_append_runtime(int handle, char *exename, char **cause_r) {
2122         char *cause= NULL, *runtime= get_runtime_path(exename);
2123         unsigned char buf[1024];
2124         int count, progfd= -1;
2125
2126         if (!runtime) {
2127                 cause= "Unable to find runtime";
2128                 goto cleanup;
2129         }
2130
2131         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2132         if (progfd==-1) {
2133                 cause= "Unable to find runtime";
2134                 goto cleanup;
2135         }
2136
2137         while ((count= read(progfd, buf, sizeof(buf)))>0) {
2138                 if (write(handle, buf, count)!=count) {
2139                         cause= "Unable to write to output file";
2140                         goto cleanup;
2141                 }
2142         }
2143
2144 cleanup:
2145         if (progfd!=-1)
2146                 close(progfd);
2147         if (runtime)
2148                 MEM_freeN(runtime);
2149
2150         if (cause) {
2151                 *cause_r= cause;
2152                 return 0;
2153         } else
2154                 return 1;
2155 }
2156
2157 static int handle_write_msb_int(int handle, int i) {
2158         unsigned char buf[4];
2159         buf[0]= (i>>24)&0xFF;
2160         buf[1]= (i>>16)&0xFF;
2161         buf[2]= (i>>8)&0xFF;
2162         buf[3]= (i>>0)&0xFF;
2163
2164         return (write(handle, buf, 4)==4);
2165 }
2166
2167 void BLO_write_runtime(char *file, char *exename) {
2168         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2169         char *cause= NULL;
2170         int datastart;
2171
2172         if (!outfd) {
2173                 cause= "Unable to open output file";
2174                 goto cleanup;
2175         }
2176         if (!handle_append_runtime(outfd, exename, &cause))
2177                 goto cleanup;
2178
2179         datastart= lseek(outfd, 0, SEEK_CUR);
2180
2181         write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
2182
2183         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
2184                 cause= "Unable to write to output file";
2185                 goto cleanup;
2186         }
2187
2188 cleanup:
2189         if (outfd!=-1)
2190                 close(outfd);
2191
2192         if (cause)
2193                 error("Unable to make runtime: %s", cause);
2194 }
2195
2196 #endif /* !__APPLE__ */