]> git.mxchange.org Git - simgear.git/blob - simgear/io/sg_binobj.cxx
- new FSF addresses
[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
35 #include <vector>
36 #include STL_STRING
37
38 #include <simgear/bucket/newbucket.hxx>
39 #include <simgear/misc/sg_path.hxx>
40
41 #include "lowlevel.hxx"
42 #include "sg_binobj.hxx"
43
44
45 SG_USING_STD( string );
46 SG_USING_STD( vector );
47
48
49 enum {
50     SG_BOUNDING_SPHERE = 0,
51
52     SG_VERTEX_LIST = 1,
53     SG_COLOR_LIST = 4,
54     SG_NORMAL_LIST = 2,
55     SG_TEXCOORD_LIST = 3,
56
57     SG_POINTS = 9,
58
59     SG_TRIANGLE_FACES = 10,
60     SG_TRIANGLE_STRIPS = 11,
61     SG_TRIANGLE_FANS = 12
62 } sgObjectTypes;
63
64 enum {
65     SG_IDX_VERTICES =  0x01,
66     SG_IDX_NORMALS =   0x02,
67     SG_IDX_COLORS =    0x04,
68     SG_IDX_TEXCOORDS = 0x08
69 } sgIndexTypes;
70
71 enum {
72     SG_MATERIAL = 0,
73     SG_INDEX_TYPES = 1
74 } sgPropertyTypes;
75
76
77 class sgSimpleBuffer {
78
79 private:
80
81     char *ptr;
82     unsigned int size;
83
84 public:
85
86     inline sgSimpleBuffer( unsigned int s )
87     {
88         size = 1;
89         while ( size < s ) {
90             size *= 2;
91         }
92         SG_LOG(SG_EVENT, SG_DEBUG, "Creating a new buffer of size = " << size);
93         ptr = new char[size];
94     }
95
96     inline ~sgSimpleBuffer() {
97         delete [] ptr;
98     }
99
100     inline unsigned int get_size() const { return size; }
101     inline char *get_ptr() const { return ptr; }
102     inline void resize( unsigned int s ) {
103         if ( s > size ) {
104             if ( ptr != NULL ) {
105                 delete [] ptr;
106             }
107             while ( size < s ) {
108                 size *= 2;
109             }
110             SG_LOG(SG_EVENT, SG_DEBUG, "resizing buffer to size = " << size);
111             ptr = new char[size];
112         }
113     }
114 };
115
116
117 // calculate the center of a list of points, by taking the halfway
118 // point between the min and max points.
119 Point3D sgCalcCenter( point_list& wgs84_nodes ) {
120     Point3D p, min, max;
121
122     if ( wgs84_nodes.size() ) {
123         min = max = wgs84_nodes[0];
124     } else {
125         min = max = Point3D( 0 );
126     }
127
128     for ( int i = 0; i < (int)wgs84_nodes.size(); ++i ) {
129         p = wgs84_nodes[i];
130
131         if ( p.x() < min.x() ) { min.setx( p.x() ); }
132         if ( p.y() < min.y() ) { min.sety( p.y() ); }
133         if ( p.z() < min.z() ) { min.setz( p.z() ); }
134
135         if ( p.x() > max.x() ) { max.setx( p.x() ); }
136         if ( p.y() > max.y() ) { max.sety( p.y() ); }
137         if ( p.z() > max.z() ) { max.setz( p.z() ); }
138     }
139
140     return ( min + max ) / 2.0;
141 }
142
143 // calculate the bounding sphere.  Center is the center of the
144 // tile and zero elevation
145 double sgCalcBoundingRadius( Point3D center, point_list& wgs84_nodes ) {
146     double dist_squared;
147     double radius_squared = 0;
148     
149     for ( int i = 0; i < (int)wgs84_nodes.size(); ++i ) {
150         dist_squared = center.distance3Dsquared( wgs84_nodes[i] );
151         if ( dist_squared > radius_squared ) {
152             radius_squared = dist_squared;
153         }
154     }
155
156     return sqrt(radius_squared);
157 }
158
159
160
161 // read object properties
162 static void read_object( gzFile fp,
163                          int obj_type,
164                          int nproperties,
165                          int nelements,
166                          group_list *vertices,
167                          group_list *normals,
168                          group_list *colors,
169                          group_list *texcoords,
170                          string_list *materials )
171 {
172     unsigned int nbytes;
173     unsigned char idx_mask;
174     int idx_size;
175     bool do_vertices, do_normals, do_colors, do_texcoords;
176     int j, k, idx;
177     static sgSimpleBuffer buf( 32768 );  // 32 Kb
178     char material[256];
179
180     // default values
181     if ( obj_type == SG_POINTS ) {
182         idx_size = 1;
183         idx_mask = SG_IDX_VERTICES;
184         do_vertices = true;
185         do_normals = false;
186         do_colors = false;
187         do_texcoords = false;
188     } else {
189         idx_size = 2;
190         idx_mask = (char)(SG_IDX_VERTICES | SG_IDX_TEXCOORDS);
191         do_vertices = true;
192         do_normals = false;
193         do_colors = false;
194         do_texcoords = true;
195     }
196
197     for ( j = 0; j < nproperties; ++j ) {
198         char prop_type;
199         sgReadChar( fp, &prop_type );
200
201         sgReadUInt( fp, &nbytes );
202         // cout << "property size = " << nbytes << endl;
203         if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
204         char *ptr = buf.get_ptr();
205         sgReadBytes( fp, nbytes, ptr );
206         if ( prop_type == SG_MATERIAL ) {
207             strncpy( material, ptr, nbytes );
208             material[nbytes] = '\0';
209             // cout << "material type = " << material << endl;
210         } else if ( prop_type == SG_INDEX_TYPES ) {
211             idx_mask = ptr[0];
212             // cout << "idx_mask = " << (int)idx_mask << endl;
213             idx_size = 0;
214             do_vertices = false;
215             do_normals = false;
216             do_colors = false;
217             do_texcoords = false;
218             if ( idx_mask & SG_IDX_VERTICES ) {
219                 do_vertices = true;
220                 ++idx_size;
221             }
222             if ( idx_mask & SG_IDX_NORMALS ) {
223                 do_normals = true;
224                 ++idx_size;
225             }
226             if ( idx_mask & SG_IDX_COLORS ) {
227                 do_colors = true;
228                 ++idx_size;
229             }
230             if ( idx_mask & SG_IDX_TEXCOORDS ) {
231                 do_texcoords = true;
232                 ++idx_size;
233             }
234         }
235     }
236
237     for ( j = 0; j < nelements; ++j ) {
238         sgReadUInt( fp, &nbytes );
239         // cout << "element size = " << nbytes << endl;
240         if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
241         char *ptr = buf.get_ptr();
242         sgReadBytes( fp, nbytes, ptr );
243         int count = nbytes / (idx_size * sizeof(unsigned short));
244         unsigned short *sptr = (unsigned short *)ptr;
245         int_list vs; vs.clear();
246         int_list ns; ns.clear();
247         int_list cs; cs.clear();
248         int_list tcs; tcs.clear();
249         for ( k = 0; k < count; ++k ) {
250             if ( sgIsBigEndian() ) {
251                 for ( idx = 0; idx < idx_size; ++idx ) {
252                     sgEndianSwap( (uint16_t *)&(sptr[idx]) );
253                 }
254             }
255             idx = 0;
256             if ( do_vertices ) {
257                 vs.push_back( sptr[idx++] );
258             }
259             if ( do_normals ) {
260                 ns.push_back( sptr[idx++] );
261                     }
262             if ( do_colors ) {
263                 cs.push_back( sptr[idx++] );
264             }
265             if ( do_texcoords ) {
266                 tcs.push_back( sptr[idx++] );
267             }
268             // cout << sptr[0] << " ";
269             sptr += idx_size;
270         }
271         // cout << endl;
272         vertices->push_back( vs );
273         normals->push_back( ns );
274         colors->push_back( cs );
275         texcoords->push_back( tcs );
276         materials->push_back( material );
277     }
278 }
279
280
281 // read a binary file and populate the provided structures.
282 bool SGBinObject::read_bin( const string& file ) {
283     Point3D p;
284     int i, j, k;
285     unsigned int nbytes;
286     static sgSimpleBuffer buf( 32768 );  // 32 Kb
287
288     // zero out structures
289     gbs_center = Point3D( 0 );
290     gbs_radius = 0.0;
291
292     wgs84_nodes.clear();
293     normals.clear();
294     texcoords.clear();
295
296     pts_v.clear();
297     pts_n.clear();
298     pts_c.clear();
299     pts_tc.clear();
300     pt_materials.clear();
301
302     tris_v.clear();
303     tris_n.clear();
304     tris_c.clear();
305     tris_tc.clear();
306     tri_materials.clear();
307
308     strips_v.clear();
309     strips_n.clear();
310     strips_c.clear();
311     strips_tc.clear();
312     strip_materials.clear();
313
314     fans_v.clear();
315     fans_n.clear();
316     fans_c.clear();
317     fans_tc.clear();
318     fan_materials.clear();
319
320     gzFile fp;
321     if ( (fp = gzopen( file.c_str(), "rb" )) == NULL ) {
322         string filegz = file + ".gz";
323         if ( (fp = gzopen( filegz.c_str(), "rb" )) == NULL ) {
324             SG_LOG( SG_EVENT, SG_ALERT,
325                "ERROR: opening " << file << " or " << filegz << "for reading!");
326
327             return false;
328         }
329     }
330
331     sgClearReadError();
332
333     // read headers
334     unsigned int header;
335     sgReadUInt( fp, &header );
336     if ( ((header & 0xFF000000) >> 24) == 'S' &&
337          ((header & 0x00FF0000) >> 16) == 'G' ) {
338         // cout << "Good header" << endl;
339         // read file version
340         version = (header & 0x0000FFFF);
341         // cout << "File version = " << version << endl;
342     } else {
343         // close the file before we return
344         gzclose(fp);
345
346         return false;
347     }
348
349     // read creation time
350     unsigned int foo_calendar_time;
351     sgReadUInt( fp, &foo_calendar_time );
352
353 #if 0
354     time_t calendar_time = foo_calendar_time;
355     // The following code has a global effect on the host application
356     // and can screws up the time elsewhere.  It should be avoided
357     // unless you need this for debugging in which case you should
358     // disable it again once the debugging task is finished.
359     struct tm *local_tm;
360     local_tm = localtime( &calendar_time );
361     char time_str[256];
362     strftime( time_str, 256, "%a %b %d %H:%M:%S %Z %Y", local_tm);
363     SG_LOG( SG_EVENT, SG_DEBUG, "File created on " << time_str);
364 #endif
365
366     // read number of top level objects
367     short nobjects;
368     sgReadShort( fp, &nobjects );
369     // cout << "Total objects to read = " << nobjects << endl;
370
371     // read in objects
372     for ( i = 0; i < nobjects; ++i ) {
373         // read object header
374         char obj_type;
375         short nproperties, nelements;
376         sgReadChar( fp, &obj_type );
377         sgReadShort( fp, &nproperties );
378         sgReadShort( fp, &nelements );
379
380         // cout << "object " << i << " = " << (int)obj_type << " props = "
381         //      << nproperties << " elements = " << nelements << endl;
382             
383         if ( obj_type == SG_BOUNDING_SPHERE ) {
384             // read bounding sphere properties
385             for ( j = 0; j < nproperties; ++j ) {
386                 char prop_type;
387                 sgReadChar( fp, &prop_type );
388
389                 sgReadUInt( fp, &nbytes );
390                 // cout << "property size = " << nbytes << endl;
391                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
392                 char *ptr = buf.get_ptr();
393                 sgReadBytes( fp, nbytes, ptr );
394             }
395
396             // read bounding sphere elements
397             for ( j = 0; j < nelements; ++j ) {
398                 sgReadUInt( fp, &nbytes );
399                 // cout << "element size = " << nbytes << endl;
400                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
401                 char *ptr = buf.get_ptr();
402                 sgReadBytes( fp, nbytes, ptr );
403
404                 double *dptr = (double *)ptr;
405                 if ( sgIsBigEndian() ) {
406                     sgEndianSwap( (uint64_t *)&(dptr[0]) );
407                     sgEndianSwap( (uint64_t *)&(dptr[1]) );
408                     sgEndianSwap( (uint64_t *)&(dptr[2]) );
409                 }
410                 gbs_center = Point3D( dptr[0], dptr[1], dptr[2] );
411                 // cout << "Center = " << gbs_center << endl;
412                 ptr += sizeof(double) * 3;
413                 
414                 float *fptr = (float *)ptr;
415                 if ( sgIsBigEndian() ) {
416                     sgEndianSwap( (uint32_t *)fptr );
417                 }
418                 gbs_radius = fptr[0];
419                 // cout << "Bounding radius = " << gbs_radius << endl;
420             }
421         } else if ( obj_type == SG_VERTEX_LIST ) {
422             // read vertex list properties
423             for ( j = 0; j < nproperties; ++j ) {
424                 char prop_type;
425                 sgReadChar( fp, &prop_type );
426
427                 sgReadUInt( fp, &nbytes );
428                 // cout << "property size = " << nbytes << endl;
429                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
430                 char *ptr = buf.get_ptr();
431                 sgReadBytes( fp, nbytes, ptr );
432             }
433
434             // read vertex list elements
435             for ( j = 0; j < nelements; ++j ) {
436                 sgReadUInt( fp, &nbytes );
437                 // cout << "element size = " << nbytes << endl;
438                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
439                 char *ptr = buf.get_ptr();
440                 sgReadBytes( fp, nbytes, ptr );
441                 int count = nbytes / (sizeof(float) * 3);
442                 float *fptr = (float *)ptr;
443                 wgs84_nodes.reserve( count );
444                 for ( k = 0; k < count; ++k ) {
445                     if ( sgIsBigEndian() ) {
446                         sgEndianSwap( (uint32_t *)&(fptr[0]) );
447                         sgEndianSwap( (uint32_t *)&(fptr[1]) );
448                         sgEndianSwap( (uint32_t *)&(fptr[2]) );
449                     }
450                     wgs84_nodes.push_back( Point3D(fptr[0], fptr[1], fptr[2]) );
451                     fptr += 3;
452                 }
453             }
454         } else if ( obj_type == SG_COLOR_LIST ) {
455             // read color list properties
456             for ( j = 0; j < nproperties; ++j ) {
457                 char prop_type;
458                 sgReadChar( fp, &prop_type );
459
460                 sgReadUInt( fp, &nbytes );
461                 // cout << "property size = " << nbytes << endl;
462                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
463                 char *ptr = buf.get_ptr();
464                 sgReadBytes( fp, nbytes, ptr );
465             }
466
467             // read color list elements
468             for ( j = 0; j < nelements; ++j ) {
469                 sgReadUInt( fp, &nbytes );
470                 // cout << "element size = " << nbytes << endl;
471                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
472                 char *ptr = buf.get_ptr();
473                 sgReadBytes( fp, nbytes, ptr );
474                 int count = nbytes / (sizeof(float) * 4);
475                 float *fptr = (float *)ptr;
476                 colors.reserve(count);
477                 for ( k = 0; k < count; ++k ) {
478                     if ( sgIsBigEndian() ) {
479                         sgEndianSwap( (uint32_t *)&(fptr[0]) );
480                         sgEndianSwap( (uint32_t *)&(fptr[1]) );
481                         sgEndianSwap( (uint32_t *)&(fptr[2]) );
482                         sgEndianSwap( (uint32_t *)&(fptr[3]) );
483                     }
484                     colors.push_back( Point3D( fptr[0], fptr[1], fptr[2] ) );
485                     fptr += 4;
486                 }
487             }
488         } else if ( obj_type == SG_NORMAL_LIST ) {
489             // read normal list properties
490             for ( j = 0; j < nproperties; ++j ) {
491                 char prop_type;
492                 sgReadChar( fp, &prop_type );
493
494                 sgReadUInt( fp, &nbytes );
495                 // cout << "property size = " << nbytes << endl;
496                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
497                 char *ptr = buf.get_ptr();
498                 sgReadBytes( fp, nbytes, ptr );
499             }
500
501             // read normal list elements
502             for ( j = 0; j < nelements; ++j ) {
503                 sgReadUInt( fp, &nbytes );
504                 // cout << "element size = " << nbytes << endl;
505                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
506                 unsigned char *ptr = (unsigned char *)(buf.get_ptr());
507                 sgReadBytes( fp, nbytes, ptr );
508                 int count = nbytes / 3;
509                 normals.reserve( count );
510                 for ( k = 0; k < count; ++k ) {
511                     sgdVec3 normal;
512                     sgdSetVec3( normal,
513                                (ptr[0]) / 127.5 - 1.0,
514                                (ptr[1]) / 127.5 - 1.0,
515                                (ptr[2]) / 127.5 - 1.0 );
516                     sgdNormalizeVec3( normal );
517
518                     normals.push_back(Point3D(normal[0], normal[1], normal[2]));
519                     ptr += 3;
520                 }
521             }
522         } else if ( obj_type == SG_TEXCOORD_LIST ) {
523             // read texcoord list properties
524             for ( j = 0; j < nproperties; ++j ) {
525                 char prop_type;
526                 sgReadChar( fp, &prop_type );
527
528                 sgReadUInt( fp, &nbytes );
529                 // cout << "property size = " << nbytes << endl;
530                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
531                 char *ptr = buf.get_ptr();
532                 sgReadBytes( fp, nbytes, ptr );
533             }
534
535             // read texcoord list elements
536             for ( j = 0; j < nelements; ++j ) {
537                 sgReadUInt( fp, &nbytes );
538                 // cout << "element size = " << nbytes << endl;
539                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
540                 char *ptr = buf.get_ptr();
541                 sgReadBytes( fp, nbytes, ptr );
542                 int count = nbytes / (sizeof(float) * 2);
543                 float *fptr = (float *)ptr;
544                 texcoords.reserve(count);
545                 for ( k = 0; k < count; ++k ) {
546                     if ( sgIsBigEndian() ) {
547                         sgEndianSwap( (uint32_t *)&(fptr[0]) );
548                         sgEndianSwap( (uint32_t *)&(fptr[1]) );
549                     }
550                     texcoords.push_back( Point3D( fptr[0], fptr[1], 0 ) );
551                     fptr += 2;
552                 }
553             }
554         } else if ( obj_type == SG_POINTS ) {
555             // read point elements
556             read_object( fp, SG_POINTS, nproperties, nelements,
557                          &pts_v, &pts_n, &pts_c, &pts_tc, &pt_materials );
558         } else if ( obj_type == SG_TRIANGLE_FACES ) {
559             // read triangle face properties
560             read_object( fp, SG_TRIANGLE_FACES, nproperties, nelements,
561                          &tris_v, &tris_n, &tris_c, &tris_tc, &tri_materials );
562         } else if ( obj_type == SG_TRIANGLE_STRIPS ) {
563             // read triangle strip properties
564             read_object( fp, SG_TRIANGLE_STRIPS, nproperties, nelements,
565                          &strips_v, &strips_n, &strips_c, &strips_tc,
566                          &strip_materials );
567         } else if ( obj_type == SG_TRIANGLE_FANS ) {
568             // read triangle fan properties
569             read_object( fp, SG_TRIANGLE_FANS, nproperties, nelements,
570                          &fans_v, &fans_n, &fans_c, &fans_tc, &fan_materials );
571         } else {
572             // unknown object type, just skip
573
574             // read properties
575             for ( j = 0; j < nproperties; ++j ) {
576                 char prop_type;
577                 sgReadChar( fp, &prop_type );
578
579                 sgReadUInt( fp, &nbytes );
580                 // cout << "property size = " << nbytes << endl;
581                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
582                 char *ptr = buf.get_ptr();
583                 sgReadBytes( fp, nbytes, ptr );
584             }
585
586             // read elements
587             for ( j = 0; j < nelements; ++j ) {
588                 sgReadUInt( fp, &nbytes );
589                 // cout << "element size = " << nbytes << endl;
590                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
591                 char *ptr = buf.get_ptr();
592                 sgReadBytes( fp, nbytes, ptr );
593             }
594         }
595     }
596
597     // close the file
598     gzclose(fp);
599
600     if ( sgReadError() ) {
601         cout << "We detected an error while reading the file." << endl;
602         return false;
603     }
604
605     return true;
606 }
607
608
609 // write out the structures to a binary file.  We assume that the
610 // groups come to us sorted by material property.  If not, things
611 // don't break, but the result won't be as optimal.
612 bool SGBinObject::write_bin( const string& base, const string& name,
613                              const SGBucket& b )
614 {
615     Point3D p;
616     sgVec2 t;
617     sgVec3 pt;
618     sgVec4 color;
619     int i, j;
620     unsigned char idx_mask;
621     int idx_size;
622
623     SGPath file = base + "/" + b.gen_base_path() + "/" + name + ".gz";
624     file.create_dir( 0755 );
625     cout << "Output file = " << file.str() << endl;
626
627     gzFile fp;
628     if ( (fp = gzopen( file.c_str(), "wb9" )) == NULL ) {
629         cout << "ERROR: opening " << file.str() << " for writing!" << endl;
630         return false;
631     }
632
633     sgClearWriteError();
634
635     cout << "points size = " << pts_v.size() << "  pt_materials = " 
636          << pt_materials.size() << endl;
637     cout << "triangles size = " << tris_v.size() << "  tri_materials = " 
638          << tri_materials.size() << endl;
639     cout << "strips size = " << strips_v.size() << "  strip_materials = " 
640          << strip_materials.size() << endl;
641     cout << "fans size = " << fans_v.size() << "  fan_materials = " 
642          << fan_materials.size() << endl;
643
644     cout << "nodes = " << wgs84_nodes.size() << endl;
645     cout << "colors = " << colors.size() << endl;
646     cout << "normals = " << normals.size() << endl;
647     cout << "tex coords = " << texcoords.size() << endl;
648
649     // write header magic
650     sgWriteUInt( fp, SG_FILE_MAGIC_NUMBER );
651     time_t calendar_time = time(NULL);
652     sgWriteLong( fp, (int32_t)calendar_time );
653
654     // calculate and write number of top level objects
655     string material;
656     int start;
657     int end;
658     short nobjects = 0;
659     nobjects++;                 // for gbs
660     nobjects++;                 // for vertices
661     nobjects++;                 // for colors
662     nobjects++;                 // for normals
663     nobjects++;                 // for texcoords
664
665     // points
666     short npts = 0;
667     start = 0; end = 1;
668     while ( start < (int)pt_materials.size() ) {
669         material = pt_materials[start];
670         while ( (end < (int)pt_materials.size()) &&
671                 (material == pt_materials[end]) ) {
672             end++;
673         }
674         npts++;
675         start = end; end = start + 1;
676     }
677     nobjects += npts;
678
679     // tris
680     short ntris = 0;
681     start = 0; end = 1;
682     while ( start < (int)tri_materials.size() ) {
683         material = tri_materials[start];
684         while ( (end < (int)tri_materials.size()) &&
685                 (material == tri_materials[end]) ) {
686             end++;
687         }
688         ntris++;
689         start = end; end = start + 1;
690     }
691     nobjects += ntris;
692
693     // strips
694     short nstrips = 0;
695     start = 0; end = 1;
696     while ( start < (int)strip_materials.size() ) {
697         material = strip_materials[start];
698         while ( (end < (int)strip_materials.size()) &&
699                 (material == strip_materials[end]) ) {
700             end++;
701         }
702         nstrips++;
703         start = end; end = start + 1;
704     }
705     nobjects += nstrips;
706
707     // fans
708     short nfans = 0;
709     start = 0; end = 1;
710     while ( start < (int)fan_materials.size() ) {
711         material = fan_materials[start];
712         while ( (end < (int)fan_materials.size()) &&
713                 (material == fan_materials[end]) ) {
714             end++;
715         }
716         nfans++;
717         start = end; end = start + 1;
718     }
719     nobjects += nfans;
720
721     cout << "total top level objects = " << nobjects << endl;
722     sgWriteShort( fp, nobjects );
723
724     // write bounding sphere
725     sgWriteChar( fp, (char)SG_BOUNDING_SPHERE );        // type
726     sgWriteShort( fp, 0 );                              // nproperties
727     sgWriteShort( fp, 1 );                              // nelements
728
729     sgWriteUInt( fp, sizeof(double) * 3 + sizeof(float) ); // nbytes
730     sgdVec3 center;
731     sgdSetVec3( center, gbs_center.x(), gbs_center.y(), gbs_center.z() );
732     sgWritedVec3( fp, center );
733     sgWriteFloat( fp, gbs_radius );
734
735     // dump vertex list
736     sgWriteChar( fp, (char)SG_VERTEX_LIST );             // type
737     sgWriteShort( fp, 0 );                               // nproperties
738     sgWriteShort( fp, 1 );                               // nelements
739     sgWriteUInt( fp, wgs84_nodes.size() * sizeof(float) * 3 ); // nbytes
740     for ( i = 0; i < (int)wgs84_nodes.size(); ++i ) {
741         p = wgs84_nodes[i] - gbs_center;
742         sgSetVec3( pt, p.x(), p.y(), p.z() );
743         sgWriteVec3( fp, pt );
744     }
745
746     // dump vertex color list
747     sgWriteChar( fp, (char)SG_COLOR_LIST );             // type
748     sgWriteShort( fp, 0 );                               // nproperties
749     sgWriteShort( fp, 1 );                               // nelements
750     sgWriteUInt( fp, colors.size() * sizeof(float) * 4 ); // nbytes
751     for ( i = 0; i < (int)colors.size(); ++i ) {
752         p = colors[i];
753         // Right now we have a place holder for color alpha but we
754         // need to update the interface so the calling program can
755         // provide the info.
756         sgSetVec4( color, p.x(), p.y(), p.z(), 1.0 );
757         sgWriteVec4( fp, color );
758     }
759
760     // dump vertex normal list
761     sgWriteChar( fp, (char)SG_NORMAL_LIST );            // type
762     sgWriteShort( fp, 0 );                              // nproperties
763     sgWriteShort( fp, 1 );                              // nelements
764     sgWriteUInt( fp, normals.size() * 3 );              // nbytes
765     char normal[3];
766     for ( i = 0; i < (int)normals.size(); ++i ) {
767         p = normals[i];
768         normal[0] = (unsigned char)((p.x() + 1.0) * 127.5);
769         normal[1] = (unsigned char)((p.y() + 1.0) * 127.5);
770         normal[2] = (unsigned char)((p.z() + 1.0) * 127.5);
771         sgWriteBytes( fp, 3, normal );
772     }
773
774     // dump texture coordinates
775     sgWriteChar( fp, (char)SG_TEXCOORD_LIST );          // type
776     sgWriteShort( fp, 0 );                              // nproperties
777     sgWriteShort( fp, 1 );                              // nelements
778     sgWriteUInt( fp, texcoords.size() * sizeof(float) * 2 ); // nbytes
779     for ( i = 0; i < (int)texcoords.size(); ++i ) {
780         p = texcoords[i];
781         sgSetVec2( t, p.x(), p.y() );
782         sgWriteVec2( fp, t );
783     }
784
785     // dump point groups if they exist
786     if ( pts_v.size() > 0 ) {
787         int start = 0;
788         int end = 1;
789         string material;
790         while ( start < (int)pt_materials.size() ) {
791             // find next group
792             material = pt_materials[start];
793             while ( (end < (int)pt_materials.size()) && 
794                     (material == pt_materials[end]) )
795                 {
796                     // cout << "end = " << end << endl;
797                     end++;
798                 }
799             // cout << "group = " << start << " to " << end - 1 << endl;
800
801             // write group headers
802             sgWriteChar( fp, (char)SG_POINTS );          // type
803             sgWriteShort( fp, 2 );                       // nproperties
804             sgWriteShort( fp, end - start );             // nelements
805
806             sgWriteChar( fp, (char)SG_MATERIAL );        // property
807             sgWriteUInt( fp, material.length() );        // nbytes
808             sgWriteBytes( fp, material.length(), material.c_str() );
809
810             idx_mask = 0;
811             idx_size = 0;
812             if ( pts_v.size() ) { idx_mask |= SG_IDX_VERTICES; ++idx_size; }
813             if ( pts_n.size() ) { idx_mask |= SG_IDX_NORMALS; ++idx_size; }
814             if ( pts_c.size() ) { idx_mask |= SG_IDX_COLORS; ++idx_size; }
815             if ( pts_tc.size() ) { idx_mask |= SG_IDX_TEXCOORDS; ++idx_size; }
816             sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
817             sgWriteUInt( fp, 1 );                        // nbytes
818             sgWriteChar( fp, idx_mask );
819
820             // write strips
821             for ( i = start; i < end; ++i ) {
822                 // nbytes
823                 sgWriteUInt( fp, pts_v[i].size() * idx_size * sizeof(short) );
824                 for ( j = 0; j < (int)pts_v[i].size(); ++j ) {
825                     if ( pts_v.size() ) { 
826                         sgWriteShort( fp, (short)pts_v[i][j] );
827                     }
828                     if ( pts_n.size() ) { 
829                         sgWriteShort( fp, (short)pts_n[i][j] );
830                     }
831                     if ( pts_c.size() ) { 
832                         sgWriteShort( fp, (short)pts_c[i][j] );
833                     }
834                     if ( pts_tc.size() ) { 
835                         sgWriteShort( fp, (short)pts_tc[i][j] );
836                     }
837                 }
838             }
839             
840             start = end;
841             end = start + 1;
842         }
843     }
844
845     // dump individual triangles if they exist
846     if ( tris_v.size() > 0 ) {
847         int start = 0;
848         int end = 1;
849         string material;
850         while ( start < (int)tri_materials.size() ) {
851             // find next group
852             material = tri_materials[start];
853             while ( (end < (int)tri_materials.size()) && 
854                     (material == tri_materials[end]) &&
855                     3*(end-start) < 32760 )
856             {
857                 // cout << "end = " << end << endl;
858                 end++;
859             }
860             // cout << "group = " << start << " to " << end - 1 << endl;
861
862             // write group headers
863             sgWriteChar( fp, (char)SG_TRIANGLE_FACES ); // type
864             sgWriteShort( fp, 2 );                      // nproperties
865             sgWriteShort( fp, 1 );                      // nelements
866
867             sgWriteChar( fp, (char)SG_MATERIAL );       // property
868             sgWriteUInt( fp, material.length() );        // nbytes
869             sgWriteBytes( fp, material.length(), material.c_str() );
870
871             idx_mask = 0;
872             idx_size = 0;
873             if ( tris_v.size() ) { idx_mask |= SG_IDX_VERTICES; ++idx_size; }
874             if ( tris_n.size() ) { idx_mask |= SG_IDX_NORMALS; ++idx_size; }
875             if ( tris_c.size() ) { idx_mask |= SG_IDX_COLORS; ++idx_size; }
876             if ( tris_tc.size() ) { idx_mask |= SG_IDX_TEXCOORDS; ++idx_size; }
877             sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
878             sgWriteUInt( fp, 1 );                        // nbytes
879             sgWriteChar( fp, idx_mask );
880
881             // nbytes
882             sgWriteUInt( fp, (end - start) * 3 * idx_size * sizeof(short) );
883
884             // write group
885             for ( i = start; i < end; ++i ) {
886                 for ( j = 0; j < 3; ++j ) {
887                     if ( tris_v.size() ) {
888                         sgWriteShort( fp, (short)tris_v[i][j] );
889                     }
890                     if ( tris_n.size() ) {
891                         sgWriteShort( fp, (short)tris_n[i][j] );
892                     }
893                     if ( tris_c.size() ) {
894                         sgWriteShort( fp, (short)tris_c[i][j] );
895                     }
896                     if ( tris_tc.size() ) {
897                         sgWriteShort( fp, (short)tris_tc[i][j] );
898                     }
899                 }
900             }
901
902             start = end;
903             end = start + 1;
904         }
905     }
906
907     // dump triangle strips
908     if ( strips_v.size() > 0 ) {
909         int start = 0;
910         int end = 1;
911         string material;
912         while ( start < (int)strip_materials.size() ) {
913             // find next group
914             material = strip_materials[start];
915             while ( (end < (int)strip_materials.size()) && 
916                     (material == strip_materials[end]) )
917                 {
918                     // cout << "end = " << end << endl;
919                     end++;
920                 }
921             // cout << "group = " << start << " to " << end - 1 << endl;
922
923             // write group headers
924             sgWriteChar( fp, (char)SG_TRIANGLE_STRIPS ); // type
925             sgWriteShort( fp, 2 );                       // nproperties
926             sgWriteShort( fp, end - start );             // nelements
927
928             sgWriteChar( fp, (char)SG_MATERIAL );        // property
929             sgWriteUInt( fp, material.length() );        // nbytes
930             sgWriteBytes( fp, material.length(), material.c_str() );
931
932             idx_mask = 0;
933             idx_size = 0;
934             if ( strips_v.size() ) { idx_mask |= SG_IDX_VERTICES; ++idx_size; }
935             if ( strips_n.size() ) { idx_mask |= SG_IDX_NORMALS; ++idx_size; }
936             if ( strips_c.size() ) { idx_mask |= SG_IDX_COLORS; ++idx_size; }
937             if ( strips_tc.size() ) { idx_mask |= SG_IDX_TEXCOORDS; ++idx_size;}
938             sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
939             sgWriteUInt( fp, 1 );                        // nbytes
940             sgWriteChar( fp, idx_mask );
941
942             // write strips
943             for ( i = start; i < end; ++i ) {
944                 // nbytes
945                 sgWriteUInt( fp, strips_v[i].size() * idx_size * sizeof(short));
946                 for ( j = 0; j < (int)strips_v[i].size(); ++j ) {
947                     if ( strips_v.size() ) { 
948                         sgWriteShort( fp, (short)strips_v[i][j] );
949                     }
950                     if ( strips_n.size() ) { 
951                         sgWriteShort( fp, (short)strips_n[i][j] );
952                     }
953                     if ( strips_c.size() ) { 
954                         sgWriteShort( fp, (short)strips_c[i][j] );
955                     }
956                     if ( strips_tc.size() ) { 
957                         sgWriteShort( fp, (short)strips_tc[i][j] );
958                     }
959                 }
960             }
961             
962             start = end;
963             end = start + 1;
964         }
965     }
966
967     // dump triangle fans
968     if ( fans_v.size() > 0 ) {
969         int start = 0;
970         int end = 1;
971         string material;
972         while ( start < (int)fan_materials.size() ) {
973             // find next group
974             material = fan_materials[start];
975             while ( (end < (int)fan_materials.size()) && 
976                     (material == fan_materials[end]) )
977                 {
978                     // cout << "end = " << end << endl;
979                     end++;
980                 }
981             // cout << "group = " << start << " to " << end - 1 << endl;
982
983             // write group headers
984             sgWriteChar( fp, (char)SG_TRIANGLE_FANS );   // type
985             sgWriteShort( fp, 2 );                       // nproperties
986             sgWriteShort( fp, end - start );             // nelements
987
988             sgWriteChar( fp, (char)SG_MATERIAL );       // property
989             sgWriteUInt( fp, material.length() );        // nbytes
990             sgWriteBytes( fp, material.length(), material.c_str() );
991
992             idx_mask = 0;
993             idx_size = 0;
994             if ( fans_v.size() ) { idx_mask |= SG_IDX_VERTICES; ++idx_size; }
995             if ( fans_n.size() ) { idx_mask |= SG_IDX_NORMALS; ++idx_size; }
996             if ( fans_c.size() ) { idx_mask |= SG_IDX_COLORS; ++idx_size; }
997             if ( fans_tc.size() ) { idx_mask |= SG_IDX_TEXCOORDS; ++idx_size; }
998             sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
999             sgWriteUInt( fp, 1 );                        // nbytes
1000             sgWriteChar( fp, idx_mask );
1001
1002             // write fans
1003             for ( i = start; i < end; ++i ) {
1004                 // nbytes
1005                 sgWriteUInt( fp, fans_v[i].size() * idx_size * sizeof(short) );
1006                 for ( j = 0; j < (int)fans_v[i].size(); ++j ) {
1007                     if ( fans_v.size() ) {
1008                         sgWriteShort( fp, (short)fans_v[i][j] );
1009                     }
1010                     if ( fans_n.size() ) {
1011                         sgWriteShort( fp, (short)fans_n[i][j] );
1012                     }
1013                     if ( fans_c.size() ) {
1014                         sgWriteShort( fp, (short)fans_c[i][j] );
1015                     }
1016                     if ( fans_tc.size() ) {
1017                         sgWriteShort( fp, (short)fans_tc[i][j] );
1018                     }
1019                 }
1020             }
1021             
1022             start = end;
1023             end = start + 1;
1024         }
1025     }
1026
1027     // close the file
1028     gzclose(fp);
1029
1030     if ( sgWriteError() ) {
1031         cout << "We detected an error while writing the file." << endl;
1032         return false;
1033     }
1034
1035     return true;
1036 }
1037
1038
1039 // write out the structures to an ASCII file.  We assume that the
1040 // groups come to us sorted by material property.  If not, things
1041 // don't break, but the result won't be as optimal.
1042 bool SGBinObject::write_ascii( const string& base, const string& name,
1043                                const SGBucket& b )
1044 {
1045     Point3D p;
1046     int i, j;
1047
1048     SGPath file = base + "/" + b.gen_base_path() + "/" + name;
1049     file.create_dir( 0755 );
1050     cout << "Output file = " << file.str() << endl;
1051
1052     FILE *fp;
1053     if ( (fp = fopen( file.c_str(), "w" )) == NULL ) {
1054         cout << "ERROR: opening " << file.str() << " for writing!" << endl;
1055         return false;
1056     }
1057
1058     cout << "triangles size = " << tris_v.size() << "  tri_materials = " 
1059          << tri_materials.size() << endl;
1060     cout << "strips size = " << strips_v.size() << "  strip_materials = " 
1061          << strip_materials.size() << endl;
1062     cout << "fans size = " << fans_v.size() << "  fan_materials = " 
1063          << fan_materials.size() << endl;
1064
1065     cout << "points = " << wgs84_nodes.size() << endl;
1066     cout << "tex coords = " << texcoords.size() << endl;
1067     // write headers
1068     fprintf(fp, "# FGFS Scenery\n");
1069     fprintf(fp, "# Version %s\n", SG_SCENERY_FILE_FORMAT);
1070
1071     time_t calendar_time = time(NULL);
1072     struct tm *local_tm;
1073     local_tm = localtime( &calendar_time );
1074     char time_str[256];
1075     strftime( time_str, 256, "%a %b %d %H:%M:%S %Z %Y", local_tm);
1076     fprintf(fp, "# Created %s\n", time_str );
1077     fprintf(fp, "\n");
1078
1079     // write bounding sphere
1080     fprintf(fp, "# gbs %.5f %.5f %.5f %.2f\n",
1081             gbs_center.x(), gbs_center.y(), gbs_center.z(), gbs_radius);
1082     fprintf(fp, "\n");
1083
1084     // dump vertex list
1085     fprintf(fp, "# vertex list\n");
1086     for ( i = 0; i < (int)wgs84_nodes.size(); ++i ) {
1087         p = wgs84_nodes[i] - gbs_center;
1088         
1089         fprintf(fp,  "v %.5f %.5f %.5f\n", p.x(), p.y(), p.z() );
1090     }
1091     fprintf(fp, "\n");
1092
1093     fprintf(fp, "# vertex normal list\n");
1094     for ( i = 0; i < (int)normals.size(); ++i ) {
1095         p = normals[i];
1096         fprintf(fp,  "vn %.5f %.5f %.5f\n", p.x(), p.y(), p.z() );
1097     }
1098     fprintf(fp, "\n");
1099
1100     // dump texture coordinates
1101     fprintf(fp, "# texture coordinate list\n");
1102     for ( i = 0; i < (int)texcoords.size(); ++i ) {
1103         p = texcoords[i];
1104         fprintf(fp,  "vt %.5f %.5f\n", p.x(), p.y() );
1105     }
1106     fprintf(fp, "\n");
1107
1108     // dump individual triangles if they exist
1109     if ( tris_v.size() > 0 ) {
1110         fprintf(fp, "# triangle groups\n");
1111
1112         int start = 0;
1113         int end = 1;
1114         string material;
1115         while ( start < (int)tri_materials.size() ) {
1116             // find next group
1117             material = tri_materials[start];
1118             while ( (end < (int)tri_materials.size()) && 
1119                     (material == tri_materials[end]) )
1120             {
1121                 // cout << "end = " << end << endl;
1122                 end++;
1123             }
1124             // cout << "group = " << start << " to " << end - 1 << endl;
1125
1126             // make a list of points for the group
1127             point_list group_nodes;
1128             group_nodes.clear();
1129             Point3D bs_center;
1130             double bs_radius = 0;
1131             for ( i = start; i < end; ++i ) {
1132                 for ( j = 0; j < (int)tris_v[i].size(); ++j ) {
1133                     group_nodes.push_back( wgs84_nodes[ tris_v[i][j] ] );
1134                     bs_center = sgCalcCenter( group_nodes );
1135                     bs_radius = sgCalcBoundingRadius( bs_center, group_nodes );
1136                 }
1137             }
1138
1139             // write group headers
1140             fprintf(fp, "\n");
1141             fprintf(fp, "# usemtl %s\n", material.c_str());
1142             fprintf(fp, "# bs %.4f %.4f %.4f %.2f\n",
1143                     bs_center.x(), bs_center.y(), bs_center.z(), bs_radius);
1144
1145             // write groups
1146             for ( i = start; i < end; ++i ) {
1147                 fprintf(fp, "f");
1148                 for ( j = 0; j < (int)tris_v[i].size(); ++j ) {
1149                     fprintf(fp, " %d/%d", tris_v[i][j], tris_tc[i][j] );
1150                 }
1151                 fprintf(fp, "\n");
1152             }
1153
1154             start = end;
1155             end = start + 1;
1156         }
1157     }
1158
1159     // dump triangle groups
1160     if ( strips_v.size() > 0 ) {
1161         fprintf(fp, "# triangle strips\n");
1162
1163         int start = 0;
1164         int end = 1;
1165         string material;
1166         while ( start < (int)strip_materials.size() ) {
1167             // find next group
1168             material = strip_materials[start];
1169             while ( (end < (int)strip_materials.size()) && 
1170                     (material == strip_materials[end]) )
1171                 {
1172                     // cout << "end = " << end << endl;
1173                     end++;
1174                 }
1175             // cout << "group = " << start << " to " << end - 1 << endl;
1176
1177             // make a list of points for the group
1178             point_list group_nodes;
1179             group_nodes.clear();
1180             Point3D bs_center;
1181             double bs_radius = 0;
1182             for ( i = start; i < end; ++i ) {
1183                 for ( j = 0; j < (int)strips_v[i].size(); ++j ) {
1184                     group_nodes.push_back( wgs84_nodes[ strips_v[i][j] ] );
1185                     bs_center = sgCalcCenter( group_nodes );
1186                     bs_radius = sgCalcBoundingRadius( bs_center, group_nodes );
1187                 }
1188             }
1189
1190             // write group headers
1191             fprintf(fp, "\n");
1192             fprintf(fp, "# usemtl %s\n", material.c_str());
1193             fprintf(fp, "# bs %.4f %.4f %.4f %.2f\n",
1194                     bs_center.x(), bs_center.y(), bs_center.z(), bs_radius);
1195
1196             // write groups
1197             for ( i = start; i < end; ++i ) {
1198                 fprintf(fp, "ts");
1199                 for ( j = 0; j < (int)strips_v[i].size(); ++j ) {
1200                     fprintf(fp, " %d/%d", strips_v[i][j], strips_tc[i][j] );
1201                 }
1202                 fprintf(fp, "\n");
1203             }
1204             
1205             start = end;
1206             end = start + 1;
1207         }
1208     }
1209
1210     // close the file
1211     fclose(fp);
1212
1213     string command = "gzip --force --best " + file.str();
1214     system(command.c_str());
1215
1216     return true;
1217 }