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