]> git.mxchange.org Git - simgear.git/blob - simgear/io/sg_binobj.cxx
HTTP: Rename urlretrieve/urlload to save/load.
[simgear.git] / simgear / io / sg_binobj.cxx
1 // sg_binobj.cxx -- routines to read and write low level flightgear 3d objects
2 //
3 // Written by Curtis Olson, started January 2000.
4 //
5 // Copyright (C) 2000  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
7 // This program is free software; you can redistribute it and/or modify
8 // it under the terms of the GNU General Public License as published by
9 // the Free Software Foundation; either version 2 of the License, or
10 // (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 // GNU General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22 //
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <simgear_config.h>
27 #endif
28
29 #include <simgear/compiler.h>
30 #include <simgear/debug/logstream.hxx>
31
32 #include <stdio.h>
33 #include <time.h>
34 #include <cstring>
35 #include <cstdlib> // for system()
36 #include <cassert>
37
38 #include <vector>
39 #include <string>
40 #include <iostream>
41 #include <bitset>
42
43 #include <simgear/bucket/newbucket.hxx>
44 #include <simgear/misc/sg_path.hxx>
45 #include <simgear/math/SGGeometry.hxx>
46 #include <simgear/structure/exception.hxx>
47
48 #include "lowlevel.hxx"
49 #include "sg_binobj.hxx"
50
51
52 using std::string;
53 using std::vector;
54 using std::cout;
55 using std::endl;
56
57 enum sgObjectTypes {
58     SG_BOUNDING_SPHERE = 0,
59
60     SG_VERTEX_LIST = 1,
61     SG_COLOR_LIST = 4,
62     SG_NORMAL_LIST = 2,
63     SG_TEXCOORD_LIST = 3,
64
65     SG_POINTS = 9,
66
67     SG_TRIANGLE_FACES = 10,
68     SG_TRIANGLE_STRIPS = 11,
69     SG_TRIANGLE_FANS = 12
70 };
71
72 enum sgIndexTypes {
73     SG_IDX_VERTICES =  0x01,
74     SG_IDX_NORMALS =   0x02,
75     SG_IDX_COLORS =    0x04,
76     SG_IDX_TEXCOORDS = 0x08
77 };
78
79 enum sgPropertyTypes {
80     SG_MATERIAL = 0,
81     SG_INDEX_TYPES = 1
82 };
83
84
85 class sgSimpleBuffer {
86
87 private:
88
89     char *ptr;
90     unsigned int size;
91     size_t offset;
92 public:
93
94     sgSimpleBuffer( unsigned int s = 0) :
95         ptr(NULL),
96         size(0),
97         offset(0)
98     {
99         resize(s);
100     }
101
102     ~sgSimpleBuffer()
103     {
104         delete [] ptr;
105     }
106
107     unsigned int get_size() const { return size; }
108     char *get_ptr() const { return ptr; }
109     
110     void reset()
111     {
112         offset = 0;
113     }
114     
115     void resize( unsigned int s )
116     {
117         if ( s > size ) {
118             if ( ptr != NULL ) {
119                 delete [] ptr;
120             }
121           
122             if ( size == 0) {
123                 size = 16;
124             }
125           
126             while ( size < s ) {
127               size = size << 1;
128             }
129             ptr = new char[size];
130         }
131     }
132     
133     SGVec3d readVec3d()
134     {
135         double* p = reinterpret_cast<double*>(ptr + offset);
136         
137         if ( sgIsBigEndian() ) {            
138             sgEndianSwap((uint64_t *) p + 0);
139             sgEndianSwap((uint64_t *) p + 1);
140             sgEndianSwap((uint64_t *) p + 2);
141         }
142         
143         offset += 3 * sizeof(double);
144         return SGVec3d(p);
145     }
146     
147     float readFloat()
148     {
149         float* p = reinterpret_cast<float*>(ptr + offset);
150         if ( sgIsBigEndian() ) {            
151             sgEndianSwap((uint32_t *) p);
152         }
153         
154         offset += sizeof(float);
155         return *p;
156     }
157     
158     SGVec2f readVec2f()
159     {
160         float* p = reinterpret_cast<float*>(ptr + offset);
161         
162         if ( sgIsBigEndian() ) {            
163             sgEndianSwap((uint32_t *) p + 0);
164             sgEndianSwap((uint32_t *) p + 1);
165         }
166         
167         offset += 2 * sizeof(float);
168         return SGVec2f(p);
169     }
170     
171     SGVec3f readVec3f()
172     {
173         float* p = reinterpret_cast<float*>(ptr + offset);
174         
175         if ( sgIsBigEndian() ) {            
176             sgEndianSwap((uint32_t *) p + 0);
177             sgEndianSwap((uint32_t *) p + 1);
178             sgEndianSwap((uint32_t *) p + 2);
179         }
180         
181         offset += 3 * sizeof(float);
182         return SGVec3f(p);
183     }
184     
185     SGVec4f readVec4f()
186     {
187         float* p = reinterpret_cast<float*>(ptr + offset);
188         
189         if ( sgIsBigEndian() ) {            
190             sgEndianSwap((uint32_t *) p + 0);
191             sgEndianSwap((uint32_t *) p + 1);
192             sgEndianSwap((uint32_t *) p + 2);
193             sgEndianSwap((uint32_t *) p + 3);
194         }
195         
196         offset += 4 * sizeof(float);
197         return SGVec4f(p);
198     }
199 };
200
201 template <class T>
202 static void read_indices(char* buffer, 
203                          size_t bytes,
204                          int indexMask,
205                          int_list& vertices, 
206                          int_list& normals,
207                          int_list& colors,
208                          int_list& texCoords)
209 {
210     const int indexSize = sizeof(T) * std::bitset<32>(indexMask).count();
211     const int count = bytes / indexSize;
212     
213 // fix endian-ness of the whole lot, if required
214     if (sgIsBigEndian()) {
215         int indices = bytes / sizeof(T);
216         T* src = reinterpret_cast<T*>(buffer);
217         for (int i=0; i<indices; ++i) {
218             sgEndianSwap(src++);
219         }
220     }
221     
222     T* src = reinterpret_cast<T*>(buffer);
223     for (int i=0; i<count; ++i) {
224         if (indexMask & SG_IDX_VERTICES) vertices.push_back(*src++);
225         if (indexMask & SG_IDX_NORMALS) normals.push_back(*src++);
226         if (indexMask & SG_IDX_COLORS) colors.push_back(*src++);
227         if (indexMask & SG_IDX_TEXCOORDS) texCoords.push_back(*src++);
228     } // of elements in the index
229 }
230
231 template <class T>
232 void write_indice(gzFile fp, T value)
233 {
234     sgWriteBytes(fp, sizeof(T), &value);
235 }
236
237 // specialize template to call endian-aware conversion methods
238 template <>
239 void write_indice(gzFile fp, uint16_t value)
240 {
241     sgWriteUShort(fp, value);
242 }
243
244 template <>
245 void write_indice(gzFile fp, uint32_t value)
246 {
247     sgWriteUInt(fp, value);
248 }
249
250
251 template <class T>
252 void write_indices(gzFile fp, unsigned char indexMask, 
253     const int_list& vertices, 
254     const int_list& normals, 
255     const int_list& colors,
256     const int_list& texCoords)
257 {
258     unsigned int count = vertices.size();
259     const int indexSize = sizeof(T) * std::bitset<32>(indexMask).count();
260     sgWriteUInt(fp, indexSize * count);
261             
262     for (unsigned int i=0; i < count; ++i) {
263         write_indice(fp, static_cast<T>(vertices[i]));
264         
265         if (indexMask & SG_IDX_NORMALS) {
266             write_indice(fp, static_cast<T>(normals[i]));
267         }
268         if (indexMask & SG_IDX_COLORS) {
269             write_indice(fp, static_cast<T>(colors[i]));
270         }
271         if (indexMask & SG_IDX_TEXCOORDS) {
272             write_indice(fp, static_cast<T>(texCoords[i]));
273         }
274     }
275 }
276
277
278 // read object properties
279 void SGBinObject::read_object( gzFile fp,
280                          int obj_type,
281                          int nproperties,
282                          int nelements,
283                          group_list& vertices, 
284                           group_list& normals,
285                           group_list& colors,
286                           group_list& texCoords,
287                           string_list& materials)
288 {
289     unsigned int nbytes;
290     unsigned char idx_mask;
291     int j;
292     sgSimpleBuffer buf( 32768 );  // 32 Kb
293     char material[256];
294
295     // default values
296     if ( obj_type == SG_POINTS ) {
297         idx_mask = SG_IDX_VERTICES;
298     } else {
299         idx_mask = (char)(SG_IDX_VERTICES | SG_IDX_TEXCOORDS);
300     }
301
302     for ( j = 0; j < nproperties; ++j ) {
303         char prop_type;
304         sgReadChar( fp, &prop_type );
305         sgReadUInt( fp, &nbytes );
306         buf.resize(nbytes);
307         char *ptr = buf.get_ptr();
308         sgReadBytes( fp, nbytes, ptr );
309         if ( prop_type == SG_MATERIAL ) {
310             if (nbytes > 255) {
311                 nbytes = 255;
312             }
313             strncpy( material, ptr, nbytes );
314             material[nbytes] = '\0';
315             // cout << "material type = " << material << endl;
316         } else if ( prop_type == SG_INDEX_TYPES ) {
317             idx_mask = ptr[0];
318             //cout << std::hex << "index mask:" << idx_mask << std::dec << endl;
319         }
320     }
321
322     if ( sgReadError() ) {
323         throw sg_exception("Error reading object properties");
324     }
325     
326     size_t indexCount = std::bitset<32>(idx_mask).count();
327     if (indexCount == 0) {
328         throw sg_exception("object index mask has no bits set");
329     }
330     
331     for ( j = 0; j < nelements; ++j ) {
332         sgReadUInt( fp, &nbytes );
333         if ( sgReadError() ) {
334             throw sg_exception("Error reading element size");
335         }
336         
337         buf.resize( nbytes );
338         char *ptr = buf.get_ptr();
339         sgReadBytes( fp, nbytes, ptr );
340         
341         if ( sgReadError() ) {
342             throw sg_exception("Error reading element bytes");
343         }
344                 
345         int_list vs;
346         int_list ns;
347         int_list cs;
348         int_list tcs;
349         if (version >= 10) {
350             read_indices<uint32_t>(ptr, nbytes, idx_mask, vs, ns, cs, tcs);
351         } else {
352             read_indices<uint16_t>(ptr, nbytes, idx_mask, vs, ns, cs, tcs);
353         }
354
355         vertices.push_back( vs );
356         normals.push_back( ns );
357         colors.push_back( cs );
358         texCoords.push_back( tcs );
359         materials.push_back( material );
360     } // of element iteration
361 }
362
363
364 // read a binary file and populate the provided structures.
365 bool SGBinObject::read_bin( const string& file ) {
366     SGVec3d p;
367     int i, k;
368     size_t j;
369     unsigned int nbytes;
370     sgSimpleBuffer buf( 32768 );  // 32 Kb
371
372     // zero out structures
373     gbs_center = SGVec3d(0, 0, 0);
374     gbs_radius = 0.0;
375
376     wgs84_nodes.clear();
377     normals.clear();
378     texcoords.clear();
379
380     pts_v.clear();
381     pts_n.clear();
382     pts_c.clear();
383     pts_tc.clear();
384     pt_materials.clear();
385
386     tris_v.clear();
387     tris_n.clear();
388     tris_c.clear();
389     tris_tc.clear();
390     tri_materials.clear();
391
392     strips_v.clear();
393     strips_n.clear();
394     strips_c.clear();
395     strips_tc.clear();
396     strip_materials.clear();
397
398     fans_v.clear();
399     fans_n.clear();
400     fans_c.clear();
401     fans_tc.clear();
402     fan_materials.clear();
403
404     gzFile fp;
405     if ( (fp = gzopen( file.c_str(), "rb" )) == NULL ) {
406         string filegz = file + ".gz";
407         if ( (fp = gzopen( filegz.c_str(), "rb" )) == NULL ) {
408             SG_LOG( SG_EVENT, SG_ALERT,
409                "ERROR: opening " << file << " or " << filegz << " for reading!");
410
411             throw sg_io_exception("Error opening for reading (and .gz)", sg_location(file));
412         }
413     }
414
415     sgClearReadError();
416
417     // read headers
418     unsigned int header;
419     sgReadUInt( fp, &header );
420     if ( ((header & 0xFF000000) >> 24) == 'S' &&
421          ((header & 0x00FF0000) >> 16) == 'G' ) {
422         // cout << "Good header" << endl;
423         // read file version
424         version = (header & 0x0000FFFF);
425         // cout << "File version = " << version << endl;
426     } else {
427         // close the file before we return
428         gzclose(fp);
429         throw sg_io_exception("Bad BTG magic/version", sg_location(file));
430     }
431     
432     // read creation time
433     unsigned int foo_calendar_time;
434     sgReadUInt( fp, &foo_calendar_time );
435
436 #if 0
437     time_t calendar_time = foo_calendar_time;
438     // The following code has a global effect on the host application
439     // and can screws up the time elsewhere.  It should be avoided
440     // unless you need this for debugging in which case you should
441     // disable it again once the debugging task is finished.
442     struct tm *local_tm;
443     local_tm = localtime( &calendar_time );
444     char time_str[256];
445     strftime( time_str, 256, "%a %b %d %H:%M:%S %Z %Y", local_tm);
446     SG_LOG( SG_EVENT, SG_DEBUG, "File created on " << time_str);
447 #endif
448
449     // read number of top level objects
450     int nobjects;
451     if ( version >= 10) { // version 10 extends everything to be 32-bit
452         sgReadInt( fp, &nobjects );
453     } else if ( version >= 7 ) {
454         uint16_t v;
455         sgReadUShort( fp, &v );
456         nobjects = v;
457     } else {
458         int16_t v;
459         sgReadShort( fp, &v );
460         nobjects = v;
461     }
462      
463      //cout << "Total objects to read = " << nobjects << endl;
464
465     if ( sgReadError() ) {
466         throw sg_io_exception("Error reading BTG file header", sg_location(file));
467     }
468     
469     // read in objects
470     for ( i = 0; i < nobjects; ++i ) {
471         // read object header
472         char obj_type;
473         uint32_t nproperties, nelements;
474         sgReadChar( fp, &obj_type );
475         if ( version >= 10 ) {
476             sgReadUInt( fp, &nproperties );
477             sgReadUInt( fp, &nelements );
478         } else if ( version >= 7 ) {
479             uint16_t v;
480             sgReadUShort( fp, &v );
481             nproperties = v;
482             sgReadUShort( fp, &v );
483             nelements = v;
484         } else {
485             int16_t v;
486             sgReadShort( fp, &v );
487             nproperties = v;
488             sgReadShort( fp, &v );
489             nelements = v;
490         }
491
492          //cout << "object " << i << " = " << (int)obj_type << " props = "
493          //     << nproperties << " elements = " << nelements << endl;
494             
495         if ( obj_type == SG_BOUNDING_SPHERE ) {
496             // read bounding sphere properties
497             read_properties( fp, nproperties );
498             
499             // read bounding sphere elements
500             for ( j = 0; j < nelements; ++j ) {
501                 sgReadUInt( fp, &nbytes );
502                 buf.resize( nbytes );
503                 buf.reset();
504                 char *ptr = buf.get_ptr();
505                 sgReadBytes( fp, nbytes, ptr );
506                 gbs_center = buf.readVec3d();
507                 gbs_radius = buf.readFloat();
508             }
509         } else if ( obj_type == SG_VERTEX_LIST ) {
510             // read vertex list properties
511             read_properties( fp, nproperties );
512
513             // read vertex list elements
514             for ( j = 0; j < nelements; ++j ) {
515                 sgReadUInt( fp, &nbytes );
516                 buf.resize( nbytes );
517                 buf.reset();
518                 char *ptr = buf.get_ptr();
519                 sgReadBytes( fp, nbytes, ptr );
520                 int count = nbytes / (sizeof(float) * 3);
521                 wgs84_nodes.reserve( count );
522                 for ( k = 0; k < count; ++k ) {
523                     SGVec3f v = buf.readVec3f();
524                 // extend from float to double, hmmm
525                     wgs84_nodes.push_back( SGVec3d(v[0], v[1], v[2]) );
526                 }
527             }
528         } else if ( obj_type == SG_COLOR_LIST ) {
529             // read color list properties
530             read_properties( fp, nproperties );
531
532             // read color list elements
533             for ( j = 0; j < nelements; ++j ) {
534                 sgReadUInt( fp, &nbytes );
535                 buf.resize( nbytes );
536                 buf.reset();
537                 char *ptr = buf.get_ptr();
538                 sgReadBytes( fp, nbytes, ptr );
539                 int count = nbytes / (sizeof(float) * 4);
540                 colors.reserve(count);
541                 for ( k = 0; k < count; ++k ) {
542                     colors.push_back( buf.readVec4f() );
543                 }
544             }
545         } else if ( obj_type == SG_NORMAL_LIST ) {
546             // read normal list properties
547             read_properties( fp, nproperties );
548
549             // read normal list elements
550             for ( j = 0; j < nelements; ++j ) {
551                 sgReadUInt( fp, &nbytes );
552                 buf.resize( nbytes );
553                 buf.reset();
554                 unsigned char *ptr = (unsigned char *)(buf.get_ptr());
555                 sgReadBytes( fp, nbytes, ptr );
556                 int count = nbytes / 3;
557                 normals.reserve( count );
558  
559                 for ( k = 0; k < count; ++k ) {
560                     SGVec3f normal( (ptr[0]) / 127.5 - 1.0,
561                                     (ptr[1]) / 127.5 - 1.0, 
562                                     (ptr[2]) / 127.5 - 1.0);
563                     normals.push_back(normalize(normal));
564                     ptr += 3;
565                 }
566             }
567         } else if ( obj_type == SG_TEXCOORD_LIST ) {
568             // read texcoord list properties
569             read_properties( fp, nproperties );
570
571             // read texcoord list elements
572             for ( j = 0; j < nelements; ++j ) {
573                 sgReadUInt( fp, &nbytes );
574                 buf.resize( nbytes );
575                 buf.reset();
576                 char *ptr = buf.get_ptr();
577                 sgReadBytes( fp, nbytes, ptr );
578                 int count = nbytes / (sizeof(float) * 2);
579                 texcoords.reserve(count);
580                 for ( k = 0; k < count; ++k ) {
581                     texcoords.push_back( buf.readVec2f() );
582                 }
583             }
584         } else if ( obj_type == SG_POINTS ) {
585             // read point elements
586             read_object( fp, SG_POINTS, nproperties, nelements,
587                          pts_v, pts_n, pts_c, pts_tc, pt_materials );
588         } else if ( obj_type == SG_TRIANGLE_FACES ) {
589             // read triangle face properties
590             read_object( fp, SG_TRIANGLE_FACES, nproperties, nelements,
591                          tris_v, tris_n, tris_c, tris_tc, tri_materials );
592         } else if ( obj_type == SG_TRIANGLE_STRIPS ) {
593             // read triangle strip properties
594             read_object( fp, SG_TRIANGLE_STRIPS, nproperties, nelements,
595                          strips_v, strips_n, strips_c, strips_tc,
596                          strip_materials );
597         } else if ( obj_type == SG_TRIANGLE_FANS ) {
598             // read triangle fan properties
599             read_object( fp, SG_TRIANGLE_FANS, nproperties, nelements,
600                          fans_v, fans_n, fans_c, fans_tc, fan_materials );
601         } else {
602             // unknown object type, just skip
603             read_properties( fp, nproperties );
604
605             // read elements
606             for ( j = 0; j < nelements; ++j ) {
607                 sgReadUInt( fp, &nbytes );
608                 // cout << "element size = " << nbytes << endl;
609                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
610                 char *ptr = buf.get_ptr();
611                 sgReadBytes( fp, nbytes, ptr );
612             }
613         }
614         
615         if ( sgReadError() ) {
616             throw sg_io_exception("Error while reading object", sg_location(file, i));
617         }
618     }
619
620     // close the file
621     gzclose(fp);
622
623     return true;
624 }
625
626 void SGBinObject::write_header(gzFile fp, int type, int nProps, int nElements)
627 {
628     sgWriteChar(fp, (unsigned char) type);
629     if (version == 7) {
630         sgWriteUShort(fp, nProps);
631         sgWriteUShort(fp, nElements);
632     } else {
633         sgWriteUInt(fp, nProps);
634         sgWriteUInt(fp, nElements);
635     }
636 }
637
638 unsigned int SGBinObject::count_objects(const string_list& materials)
639 {
640     unsigned int result = 0;
641     unsigned int start = 0, end = 1;
642     unsigned int count = materials.size();
643     string m;
644     
645     while ( start < count ) {
646         m = materials[start];
647         for (end = start+1; (end < count) && (m == materials[end]); ++end) { }     
648         ++result;
649         start = end; 
650     }
651     
652     return result;
653 }
654
655 void SGBinObject::write_objects(gzFile fp, int type, const group_list& verts,
656     const group_list& normals, const group_list& colors, 
657     const group_list& texCoords, const string_list& materials)
658 {
659     if (verts.empty()) {
660         return;
661     }
662         
663     unsigned int start = 0, end = 1;
664     string m;
665     int_list emptyList;
666     
667     while (start < materials.size()) {
668         m = materials[start];
669     // find range of objects with identical material, write out as a single object
670         for (end = start+1; (end < materials.size()) && (m == materials[end]); ++end) {}
671     
672         const int count = end - start;
673         write_header(fp, type, 2, count);
674         
675     // properties
676         sgWriteChar( fp, (char)SG_MATERIAL );        // property
677         sgWriteUInt( fp, m.length() );        // nbytes
678         sgWriteBytes( fp, m.length(), m.c_str() );
679     
680         unsigned char idx_mask = 0;
681         if ( !verts.empty() && !verts.front().empty()) idx_mask |= SG_IDX_VERTICES;
682         if ( !normals.empty() && !normals.front().empty()) idx_mask |= SG_IDX_NORMALS;
683         if ( !colors.empty() && !colors.front().empty()) idx_mask |= SG_IDX_COLORS;
684         if ( !texCoords.empty() && !texCoords.front().empty()) idx_mask |= SG_IDX_TEXCOORDS;
685         
686         if (idx_mask == 0) {
687             SG_LOG(SG_IO, SG_ALERT, "SGBinObject::write_objects: object with material:"
688                 << m << "has no indices set");
689         }
690     
691     
692         sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
693         sgWriteUInt( fp, 1 );                        // nbytes
694         sgWriteChar( fp, idx_mask );
695     
696 //        cout << "material:" << m << ", count =" << count << endl;
697     // elements
698         for (unsigned int i=start; i < end; ++i) {
699             const int_list& va(verts[i]);
700             const int_list& na((idx_mask & SG_IDX_NORMALS) ? normals[i] : emptyList);
701             const int_list& ca((idx_mask & SG_IDX_COLORS) ? colors[i] : emptyList);
702             const int_list& tca((idx_mask & SG_IDX_TEXCOORDS) ? texCoords[i] : emptyList);
703             
704             if (version == 7) {
705                 write_indices<uint16_t>(fp, idx_mask, va, na, ca, tca);
706             } else {
707                 write_indices<uint32_t>(fp, idx_mask, va, na, ca, tca);
708             }
709         }
710     
711         start = end;
712     } // of materials iteration
713 }
714
715 // write out the structures to a binary file.  We assume that the
716 // groups come to us sorted by material property.  If not, things
717 // don't break, but the result won't be as optimal.
718 bool SGBinObject::write_bin( const string& base, const string& name,
719                              const SGBucket& b )
720 {
721
722     SGPath file = base + "/" + b.gen_base_path() + "/" + name + ".gz";
723     return write_bin_file(file);
724 }
725
726 static unsigned int max_object_size( const string_list& materials )
727 {
728     unsigned int max_size = 0;
729
730     for (unsigned int start=0; start < materials.size();) {
731         string m = materials[start];
732         unsigned int end = start + 1;
733         // find range of objects with identical material, calc its size
734         for (; (end < materials.size()) && (m == materials[end]); ++end) {}
735
736         unsigned int cur_size = end - start;
737         max_size = std::max(max_size, cur_size);
738         start = end;
739     }
740
741     return max_size;
742 }
743
744 const unsigned int VERSION_7_MATERIAL_LIMIT = 0x7fff;
745
746 bool SGBinObject::write_bin_file(const SGPath& file)
747 {
748     int i;
749     
750     SGPath file2(file);
751     file2.create_dir( 0755 );
752     cout << "Output file = " << file.str() << endl;
753
754     gzFile fp;
755     if ( (fp = gzopen( file.c_str(), "wb9" )) == NULL ) {
756         cout << "ERROR: opening " << file.str() << " for writing!" << endl;
757         return false;
758     }
759
760     sgClearWriteError();
761
762     cout << "points size = " << pts_v.size() << "  pt_materials = " 
763          << pt_materials.size() << endl;
764     cout << "triangles size = " << tris_v.size() << "  tri_materials = " 
765          << tri_materials.size() << endl;
766     cout << "strips size = " << strips_v.size() << "  strip_materials = " 
767          << strip_materials.size() << endl;
768     cout << "fans size = " << fans_v.size() << "  fan_materials = " 
769          << fan_materials.size() << endl;
770
771     cout << "nodes = " << wgs84_nodes.size() << endl;
772     cout << "colors = " << colors.size() << endl;
773     cout << "normals = " << normals.size() << endl;
774     cout << "tex coords = " << texcoords.size() << endl;
775
776     version = 10;
777     bool shortMaterialsRanges = 
778         (max_object_size(pt_materials) < VERSION_7_MATERIAL_LIMIT) &&
779         (max_object_size(fan_materials) < VERSION_7_MATERIAL_LIMIT) &&
780         (max_object_size(strip_materials) < VERSION_7_MATERIAL_LIMIT) &&
781         (max_object_size(tri_materials) < VERSION_7_MATERIAL_LIMIT);
782                     
783     if ((wgs84_nodes.size() < 0xffff) &&
784         (normals.size() < 0xffff) &&
785         (texcoords.size() < 0xffff) &&
786         shortMaterialsRanges) {
787         version = 7; // use smaller indices if possible
788     }
789
790     // write header magic
791     
792     /** Magic Number for our file format */
793     #define SG_FILE_MAGIC_NUMBER  ( ('S'<<24) + ('G'<<16) + version )
794     
795     sgWriteUInt( fp, SG_FILE_MAGIC_NUMBER );
796     time_t calendar_time = time(NULL);
797     sgWriteLong( fp, (int32_t)calendar_time );
798
799     // calculate and write number of top level objects
800     int nobjects = 5; // gbs, vertices, colors, normals, texcoords
801     nobjects += count_objects(pt_materials);
802     nobjects += count_objects(tri_materials);
803     nobjects += count_objects(strip_materials);
804     nobjects += count_objects(fan_materials);
805
806     cout << "total top level objects = " << nobjects << endl;
807     if (version == 7) {
808         sgWriteUShort( fp, (uint16_t) nobjects );
809     } else {
810         sgWriteInt( fp, nobjects );
811     } 
812     
813     // write bounding sphere
814     write_header( fp, SG_BOUNDING_SPHERE, 0, 1);
815     sgWriteUInt( fp, sizeof(double) * 3 + sizeof(float) ); // nbytes
816     sgWritedVec3( fp, gbs_center );
817     sgWriteFloat( fp, gbs_radius );
818
819     // dump vertex list
820     write_header( fp, SG_VERTEX_LIST, 0, 1);
821     sgWriteUInt( fp, wgs84_nodes.size() * sizeof(float) * 3 ); // nbytes
822     for ( i = 0; i < (int)wgs84_nodes.size(); ++i ) {
823         sgWriteVec3( fp, toVec3f(wgs84_nodes[i] - gbs_center));
824     }
825
826     // dump vertex color list
827     write_header( fp, SG_COLOR_LIST, 0, 1);
828     sgWriteUInt( fp, colors.size() * sizeof(float) * 4 ); // nbytes
829     for ( i = 0; i < (int)colors.size(); ++i ) {
830       sgWriteVec4( fp, colors[i]);
831     }
832
833     // dump vertex normal list
834     write_header( fp, SG_NORMAL_LIST, 0, 1);
835     sgWriteUInt( fp, normals.size() * 3 );              // nbytes
836     char normal[3];
837     for ( i = 0; i < (int)normals.size(); ++i ) {
838         SGVec3f p = normals[i];
839         normal[0] = (unsigned char)((p.x() + 1.0) * 127.5);
840         normal[1] = (unsigned char)((p.y() + 1.0) * 127.5);
841         normal[2] = (unsigned char)((p.z() + 1.0) * 127.5);
842         sgWriteBytes( fp, 3, normal );
843     }
844
845     // dump texture coordinates
846     write_header( fp, SG_TEXCOORD_LIST, 0, 1);
847     sgWriteUInt( fp, texcoords.size() * sizeof(float) * 2 ); // nbytes
848     for ( i = 0; i < (int)texcoords.size(); ++i ) {
849       sgWriteVec2( fp, texcoords[i]);
850     }
851
852     write_objects(fp, SG_POINTS, pts_v, pts_n, pts_c, pts_tc, pt_materials);
853     write_objects(fp, SG_TRIANGLE_FACES, tris_v, tris_n, tris_c, tris_tc, tri_materials);
854     write_objects(fp, SG_TRIANGLE_STRIPS, strips_v, strips_n, strips_c, strips_tc, strip_materials);
855     write_objects(fp, SG_TRIANGLE_FANS, fans_v, fans_n, fans_c, fans_tc, fan_materials);
856     
857     // close the file
858     gzclose(fp);
859
860     if ( sgWriteError() ) {
861         cout << "Error while writing file " << file.str() << endl;
862         return false;
863     }
864
865     return true;
866 }
867
868
869 // write out the structures to an ASCII file.  We assume that the
870 // groups come to us sorted by material property.  If not, things
871 // don't break, but the result won't be as optimal.
872 bool SGBinObject::write_ascii( const string& base, const string& name,
873                                const SGBucket& b )
874 {
875     int i, j;
876
877     SGPath file = base + "/" + b.gen_base_path() + "/" + name;
878     file.create_dir( 0755 );
879     cout << "Output file = " << file.str() << endl;
880
881     FILE *fp;
882     if ( (fp = fopen( file.c_str(), "w" )) == NULL ) {
883         cout << "ERROR: opening " << file.str() << " for writing!" << endl;
884         return false;
885     }
886
887     cout << "triangles size = " << tris_v.size() << "  tri_materials = " 
888          << tri_materials.size() << endl;
889     cout << "strips size = " << strips_v.size() << "  strip_materials = " 
890          << strip_materials.size() << endl;
891     cout << "fans size = " << fans_v.size() << "  fan_materials = " 
892          << fan_materials.size() << endl;
893
894     cout << "points = " << wgs84_nodes.size() << endl;
895     cout << "tex coords = " << texcoords.size() << endl;
896     // write headers
897     fprintf(fp, "# FGFS Scenery\n");
898     fprintf(fp, "# Version %s\n", SG_SCENERY_FILE_FORMAT);
899
900     time_t calendar_time = time(NULL);
901     struct tm *local_tm;
902     local_tm = localtime( &calendar_time );
903     char time_str[256];
904     strftime( time_str, 256, "%a %b %d %H:%M:%S %Z %Y", local_tm);
905     fprintf(fp, "# Created %s\n", time_str );
906     fprintf(fp, "\n");
907
908     // write bounding sphere
909     fprintf(fp, "# gbs %.5f %.5f %.5f %.2f\n",
910             gbs_center.x(), gbs_center.y(), gbs_center.z(), gbs_radius);
911     fprintf(fp, "\n");
912
913     // dump vertex list
914     fprintf(fp, "# vertex list\n");
915     for ( i = 0; i < (int)wgs84_nodes.size(); ++i ) {
916         SGVec3d p = wgs84_nodes[i] - gbs_center;
917         
918         fprintf(fp,  "v %.5f %.5f %.5f\n", p.x(), p.y(), p.z() );
919     }
920     fprintf(fp, "\n");
921
922     fprintf(fp, "# vertex normal list\n");
923     for ( i = 0; i < (int)normals.size(); ++i ) {
924         SGVec3f p = normals[i];
925         fprintf(fp,  "vn %.5f %.5f %.5f\n", p.x(), p.y(), p.z() );
926     }
927     fprintf(fp, "\n");
928
929     // dump texture coordinates
930     fprintf(fp, "# texture coordinate list\n");
931     for ( i = 0; i < (int)texcoords.size(); ++i ) {
932         SGVec2f p = texcoords[i];
933         fprintf(fp,  "vt %.5f %.5f\n", p.x(), p.y() );
934     }
935     fprintf(fp, "\n");
936
937     // dump individual triangles if they exist
938     if ( ! tris_v.empty() ) {
939         fprintf(fp, "# triangle groups\n");
940
941         int start = 0;
942         int end = 1;
943         string material;
944         while ( start < (int)tri_materials.size() ) {
945             // find next group
946             material = tri_materials[start];
947             while ( (end < (int)tri_materials.size()) && 
948                     (material == tri_materials[end]) )
949             {
950                 // cout << "end = " << end << endl;
951                 end++;
952             }
953             // cout << "group = " << start << " to " << end - 1 << endl;
954
955       SGSphered d;
956       for ( i = start; i < end; ++i ) {
957         for ( j = 0; j < (int)tris_v[i].size(); ++j ) {
958           d.expandBy(wgs84_nodes[ tris_v[i][j] ]);
959         }
960       }
961       
962       SGVec3d bs_center = d.getCenter();
963       double bs_radius = d.getRadius();
964             
965             // write group headers
966             fprintf(fp, "\n");
967             fprintf(fp, "# usemtl %s\n", material.c_str());
968             fprintf(fp, "# bs %.4f %.4f %.4f %.2f\n",
969                     bs_center.x(), bs_center.y(), bs_center.z(), bs_radius);
970
971             // write groups
972             for ( i = start; i < end; ++i ) {
973                 fprintf(fp, "f");
974                 for ( j = 0; j < (int)tris_v[i].size(); ++j ) {
975                     fprintf(fp, " %d/%d", tris_v[i][j], tris_tc[i][j] );
976                 }
977                 fprintf(fp, "\n");
978             }
979
980             start = end;
981             end = start + 1;
982         }
983     }
984
985     // dump triangle groups
986     if ( ! strips_v.empty() ) {
987         fprintf(fp, "# triangle strips\n");
988
989         int start = 0;
990         int end = 1;
991         string material;
992         while ( start < (int)strip_materials.size() ) {
993             // find next group
994             material = strip_materials[start];
995             while ( (end < (int)strip_materials.size()) && 
996                     (material == strip_materials[end]) )
997                 {
998                     // cout << "end = " << end << endl;
999                     end++;
1000                 }
1001             // cout << "group = " << start << " to " << end - 1 << endl;
1002
1003
1004       SGSphered d;
1005       for ( i = start; i < end; ++i ) {
1006         for ( j = 0; j < (int)tris_v[i].size(); ++j ) {
1007           d.expandBy(wgs84_nodes[ tris_v[i][j] ]);
1008         }
1009       }
1010       
1011       SGVec3d bs_center = d.getCenter();
1012       double bs_radius = d.getRadius();
1013
1014             // write group headers
1015             fprintf(fp, "\n");
1016             fprintf(fp, "# usemtl %s\n", material.c_str());
1017             fprintf(fp, "# bs %.4f %.4f %.4f %.2f\n",
1018                     bs_center.x(), bs_center.y(), bs_center.z(), bs_radius);
1019
1020             // write groups
1021             for ( i = start; i < end; ++i ) {
1022                 fprintf(fp, "ts");
1023                 for ( j = 0; j < (int)strips_v[i].size(); ++j ) {
1024                     fprintf(fp, " %d/%d", strips_v[i][j], strips_tc[i][j] );
1025                 }
1026                 fprintf(fp, "\n");
1027             }
1028             
1029             start = end;
1030             end = start + 1;
1031         }
1032     }
1033
1034     // close the file
1035     fclose(fp);
1036
1037     string command = "gzip --force --best " + file.str();
1038     int err = system(command.c_str());
1039     if (err)
1040     {
1041         cout << "ERROR: gzip " << file.str() << " failed!" << endl;
1042     }
1043
1044     return (err == 0);
1045 }
1046
1047 void SGBinObject::read_properties(gzFile fp, int nproperties)
1048 {
1049     sgSimpleBuffer buf;
1050     uint32_t nbytes;
1051     
1052     // read properties
1053     for ( int j = 0; j < nproperties; ++j ) {
1054         char prop_type;
1055         sgReadChar( fp, &prop_type );
1056         sgReadUInt( fp, &nbytes );
1057         // cout << "property size = " << nbytes << endl;
1058         if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
1059         char *ptr = buf.get_ptr();
1060         sgReadBytes( fp, nbytes, ptr );
1061     }
1062 }
1063