]> git.mxchange.org Git - flightgear.git/blob - src/Objects/obj.cxx
Fixed runway-altitude problem that prevented starts at airports higher
[flightgear.git] / src / Objects / obj.cxx
1 // obj.cxx -- routines to handle "sorta" WaveFront .obj format files.
2 //
3 // Written by Curtis Olson, started October 1997.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - curt@infoplane.com
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // 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., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #ifdef SG_MATH_EXCEPTION_CLASH
29 #  include <math.h>
30 #endif
31
32 #include <stdio.h>
33 #include <string.h>
34
35 #include <simgear/compiler.h>
36 #include <simgear/io/sg_binobj.hxx>
37
38 #include STL_STRING
39 #include <map>                  // STL
40 #include <vector>               // STL
41 #include <ctype.h>              // isdigit()
42
43 #include <simgear/constants.h>
44 #include <simgear/debug/logstream.hxx>
45 #include <simgear/math/point3d.hxx>
46 #include <simgear/math/polar3d.hxx>
47 #include <simgear/math/sg_geodesy.hxx>
48 #include <simgear/math/sg_random.h>
49 #include <simgear/misc/sgstream.hxx>
50 #include <simgear/misc/stopwatch.hxx>
51 #include <simgear/misc/texcoord.hxx>
52
53 #include <Main/globals.hxx>
54 #include <Main/fg_props.hxx>
55 #include <Scenery/tileentry.hxx>
56
57 #include "matlib.hxx"
58 #include "obj.hxx"
59
60 SG_USING_STD(string);
61 SG_USING_STD(vector);
62
63
64 typedef vector < int > int_list;
65 typedef int_list::iterator int_list_iterator;
66 typedef int_list::const_iterator int_point_list_iterator;
67
68
69 static double normals[FG_MAX_NODES][3];
70 static double tex_coords[FG_MAX_NODES*3][3];
71
72
73 #define FG_TEX_CONSTANT 69.0
74
75 // Calculate texture coordinates for a given point.
76 static Point3D local_calc_tex_coords(const Point3D& node, const Point3D& ref) {
77     Point3D cp;
78     Point3D pp;
79     // double tmplon, tmplat;
80
81     // cout << "-> " << node[0] << " " << node[1] << " " << node[2] << endl;
82     // cout << "-> " << ref.x() << " " << ref.y() << " " << ref.z() << endl;
83
84     cp = Point3D( node[0] + ref.x(),
85                   node[1] + ref.y(),
86                   node[2] + ref.z() );
87
88     pp = sgCartToPolar3d(cp);
89
90     // tmplon = pp.lon() * SGD_RADIANS_TO_DEGREES;
91     // tmplat = pp.lat() * SGD_RADIANS_TO_DEGREES;
92     // cout << tmplon << " " << tmplat << endl;
93
94     pp.setx( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.x(), 11.0) );
95     pp.sety( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.y(), 11.0) );
96
97     if ( pp.x() < 0.0 ) {
98         pp.setx( pp.x() + 11.0 );
99     }
100
101     if ( pp.y() < 0.0 ) {
102         pp.sety( pp.y() + 11.0 );
103     }
104
105     // cout << pp << endl;
106
107     return(pp);
108 }
109
110
111 // Generate a generic ocean tile on the fly
112 ssgBranch *fgGenTile( const string& path, FGTileEntry *t) {
113     FGNewMat *newmat;
114
115     ssgSimpleState *state = NULL;
116
117     ssgBranch *tile = new ssgBranch () ;
118     tile -> setName ( (char *)path.c_str() ) ;
119
120     double tex_width = 1000.0;
121     // double tex_height;
122
123     // find Ocean material in the properties list
124     newmat = material_lib.find( "Ocean" );
125     if ( newmat != NULL ) {
126         // set the texture width and height values for this
127         // material
128         tex_width = newmat->get_xsize();
129         // tex_height = newmat->get_ysize();
130         
131         // set ssgState
132         state = newmat->get_state();
133     } else {
134         SG_LOG( SG_TERRAIN, SG_ALERT, 
135                 "Ack! unknown usemtl name = " << "Ocean" 
136                 << " in " << path );
137     }
138
139     // Calculate center point
140     SGBucket b = t->tile_bucket;
141     double clon = b.get_center_lon();
142     double clat = b.get_center_lat();
143     double height = b.get_height();
144     double width = b.get_width();
145
146     Point3D center = sgGeodToCart(Point3D(clon*SGD_DEGREES_TO_RADIANS,clat*SGD_DEGREES_TO_RADIANS,0.0));
147     t->center = center;
148     // cout << "center = " << center << endl;;
149     
150     // Caculate corner vertices
151     Point3D geod[4];
152     geod[0] = Point3D( clon - width/2.0, clat - height/2.0, 0.0 );
153     geod[1] = Point3D( clon + width/2.0, clat - height/2.0, 0.0 );
154     geod[2] = Point3D( clon + width/2.0, clat + height/2.0, 0.0 );
155     geod[3] = Point3D( clon - width/2.0, clat + height/2.0, 0.0 );
156
157     Point3D rad[4];
158     int i;
159     for ( i = 0; i < 4; ++i ) {
160         rad[i] = Point3D( geod[i].x() * SGD_DEGREES_TO_RADIANS, geod[i].y() * SGD_DEGREES_TO_RADIANS,
161                           geod[i].z() );
162     }
163
164     Point3D cart[4], rel[4];
165     t->nodes.clear();
166     for ( i = 0; i < 4; ++i ) {
167         cart[i] = sgGeodToCart(rad[i]);
168         rel[i] = cart[i] - center;
169         t->nodes.push_back( rel[i] );
170         // cout << "corner " << i << " = " << cart[i] << endl;
171     }
172
173     t->ncount = 4;
174
175     // Calculate bounding radius
176     t->bounding_radius = center.distance3D( cart[0] );
177     // cout << "bounding radius = " << t->bounding_radius << endl;
178
179     // Calculate normals
180     Point3D normals[4];
181     for ( i = 0; i < 4; ++i ) {
182         normals[i] = cart[i];
183         double length = normals[i].distance3D( Point3D(0.0) );
184         normals[i] /= length;
185         // cout << "normal = " << normals[i] << endl;
186     }
187
188     // Calculate texture coordinates
189     point_list geod_nodes;
190     geod_nodes.clear();
191     for ( i = 0; i < 4; ++i ) {
192         geod_nodes.push_back( geod[i] );
193     }
194     int_list rectangle;
195     rectangle.clear();
196     for ( i = 0; i < 4; ++i ) {
197         rectangle.push_back( i );
198     }
199     point_list texs = calc_tex_coords( b, geod_nodes, rectangle, 
200                                        1000.0 / tex_width );
201
202     // Allocate ssg structure
203     ssgVertexArray   *vl = new ssgVertexArray( 4 );
204     ssgNormalArray   *nl = new ssgNormalArray( 4 );
205     ssgTexCoordArray *tl = new ssgTexCoordArray( 4 );
206     ssgColourArray   *cl = new ssgColourArray( 1 );
207
208     sgVec4 color;
209     sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
210     cl->add( color );
211
212     // sgVec3 *vtlist = new sgVec3 [ 4 ];
213     // t->vec3_ptrs.push_back( vtlist );
214     // sgVec3 *vnlist = new sgVec3 [ 4 ];
215     // t->vec3_ptrs.push_back( vnlist );
216     // sgVec2 *tclist = new sgVec2 [ 4 ];
217     // t->vec2_ptrs.push_back( tclist );
218
219     sgVec2 tmp2;
220     sgVec3 tmp3;
221     for ( i = 0; i < 4; ++i ) {
222         sgSetVec3( tmp3, 
223                    rel[i].x(), rel[i].y(), rel[i].z() );
224         vl->add( tmp3 );
225
226         sgSetVec3( tmp3, 
227                    normals[i].x(), normals[i].y(), normals[i].z() );
228         nl->add( tmp3 );
229
230         sgSetVec2( tmp2, texs[i].x(), texs[i].y());
231         tl->add( tmp2 );
232     }
233     
234     ssgLeaf *leaf = 
235         new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
236
237     leaf->setState( state );
238
239     tile->addKid( leaf );
240
241     return tile;
242 }
243
244
245 static void random_pt_inside_tri( float *res,
246                                   float *n1, float *n2, float *n3 )
247 {
248     sgVec3 p1, p2, p3;
249
250     double a = sg_random();
251     double b = sg_random();
252     if ( a + b > 1.0 ) {
253         a = 1.0 - a;
254         b = 1.0 - b;
255     }
256     double c = 1 - a - b;
257
258     sgScaleVec3( p1, n1, a );
259     sgScaleVec3( p2, n2, b );
260     sgScaleVec3( p3, n3, c );
261
262     sgAddVec3( res, p1, p2 );
263     sgAddVec3( res, p3 );
264 }
265
266
267 static void gen_random_surface_points( ssgLeaf *leaf, ssgVertexArray *lights,
268                                        double factor ) {
269     int num = leaf->getNumTriangles();
270     if ( num > 0 ) {
271         short int n1, n2, n3;
272         float *p1, *p2, *p3;
273         sgVec3 result;
274
275         // generate a repeatable random seed
276         p1 = leaf->getVertex( 0 );
277         unsigned int seed = (unsigned int)p1[0];
278         sg_srandom( seed );
279
280         for ( int i = 0; i < num; ++i ) {
281             leaf->getTriangle( i, &n1, &n2, &n3 );
282             p1 = leaf->getVertex(n1);
283             p2 = leaf->getVertex(n2);
284             p3 = leaf->getVertex(n3);
285             double area = sgTriArea( p1, p2, p3 );
286             double num = area / factor;
287
288             // generate a light point for each unit of area
289             while ( num > 1.0 ) {
290                 random_pt_inside_tri( result, p1, p2, p3 );
291                 lights->add( result );
292                 num -= 1.0;
293             }
294             // for partial units of area, use a zombie door method to
295             // create the proper random chance of a light being created
296             // for this triangle
297             if ( num > 0.0 ) {
298                 if ( sg_random() <= num ) {
299                     // a zombie made it through our door
300                     random_pt_inside_tri( result, p1, p2, p3 );
301                     lights->add( result );
302                 }
303             }
304         }
305     }
306 }
307
308
309 // Load an Ascii obj file
310 ssgBranch *fgAsciiObjLoad( const string& path, FGTileEntry *t,
311                                   ssgVertexArray *lights, const bool is_base)
312 {
313     FGNewMat *newmat = NULL;
314     string material;
315     float coverage = -1;
316     Point3D pp;
317     // sgVec3 approx_normal;
318     // double normal[3], scale = 0.0;
319     // double x, y, z, xmax, xmin, ymax, ymin, zmax, zmin;
320     // GLfloat sgenparams[] = { 1.0, 0.0, 0.0, 0.0 };
321     // GLint display_list = 0;
322     int shading;
323     bool in_faces = false;
324     int vncount, vtcount;
325     int n1 = 0, n2 = 0, n3 = 0;
326     int tex;
327     // int last1 = 0, last2 = 0;
328     bool odd = false;
329     point_list nodes;
330     Point3D node;
331     Point3D center;
332     double scenery_version = 0.0;
333     double tex_width = 1000.0, tex_height = 1000.0;
334     bool shared_done = false;
335     int_list fan_vertices;
336     int_list fan_tex_coords;
337     int i;
338     ssgSimpleState *state = NULL;
339     sgVec3 *vtlist, *vnlist;
340     sgVec2 *tclist;
341
342     ssgBranch *tile = new ssgBranch () ;
343
344     tile -> setName ( (char *)path.c_str() ) ;
345
346     // Attempt to open "path.gz" or "path"
347     sg_gzifstream in( path );
348     if ( ! in.is_open() ) {
349         SG_LOG( SG_TERRAIN, SG_DEBUG, "Cannot open file: " << path );
350         SG_LOG( SG_TERRAIN, SG_DEBUG, "default to ocean tile: " << path );
351
352         return NULL;
353     }
354
355     shading = fgGetBool("/sim/rendering/shading");
356
357     if ( is_base ) {
358         t->ncount = 0;
359     }
360     vncount = 0;
361     vtcount = 0;
362     if ( is_base ) {
363         t->bounding_radius = 0.0;
364     }
365     center = t->center;
366
367     StopWatch stopwatch;
368     stopwatch.start();
369
370     // ignore initial comments and blank lines. (priming the pump)
371     // in >> skipcomment;
372     // string line;
373
374     string token;
375     char c;
376
377 #ifdef __MWERKS__
378     while ( in.get(c) && c  != '\0' ) {
379         in.putback(c);
380 #else
381     while ( ! in.eof() ) {
382 #endif
383
384         in >> ::skipws;
385
386         if ( in.get( c ) && c == '#' ) {
387             // process a comment line
388
389             // getline( in, line );
390             // cout << "comment = " << line << endl;
391
392             in >> token;
393
394             if ( token == "Version" ) {
395                 // read scenery versions number
396                 in >> scenery_version;
397                 // cout << "scenery_version = " << scenery_version << endl;
398                 if ( scenery_version > 0.4 ) {
399                     SG_LOG( SG_TERRAIN, SG_ALERT, 
400                             "\nYou are attempting to load a tile format that\n"
401                             << "is newer than this version of flightgear can\n"
402                             << "handle.  You should upgrade your copy of\n"
403                             << "FlightGear to the newest version.  For\n"
404                             << "details, please see:\n"
405                             << "\n    http://www.flightgear.org\n" );
406                     exit(-1);
407                 }
408             } else if ( token == "gbs" ) {
409                 // reference point (center offset)
410                 if ( is_base ) {
411                     in >> t->center >> t->bounding_radius;
412                 } else {
413                     Point3D junk1;
414                     double junk2;
415                     in >> junk1 >> junk2;
416                 }
417                 center = t->center;
418                 // cout << "center = " << center 
419                 //      << " radius = " << t->bounding_radius << endl;
420             } else if ( token == "bs" ) {
421                 // reference point (center offset)
422                 // (skip past this)
423                 Point3D junk1;
424                 double junk2;
425                 in >> junk1 >> junk2;
426             } else if ( token == "usemtl" ) {
427                 // material property specification
428
429                 // if first usemtl with shared_done = false, then set
430                 // shared_done true and build the ssg shared lists
431                 if ( ! shared_done ) {
432                     // sanity check
433                     if ( (int)nodes.size() != vncount ) {
434                         SG_LOG( SG_TERRAIN, SG_ALERT, 
435                                 "Tile has mismatched nodes = " << nodes.size()
436                                 << " and normals = " << vncount << " : " 
437                                 << path );
438                         // exit(-1);
439                     }
440                     shared_done = true;
441
442                     vtlist = new sgVec3 [ nodes.size() ];
443                     t->vec3_ptrs.push_back( vtlist );
444                     vnlist = new sgVec3 [ vncount ];
445                     t->vec3_ptrs.push_back( vnlist );
446                     tclist = new sgVec2 [ vtcount ];
447                     t->vec2_ptrs.push_back( tclist );
448
449                     for ( i = 0; i < (int)nodes.size(); ++i ) {
450                         sgSetVec3( vtlist[i], 
451                                    nodes[i][0], nodes[i][1], nodes[i][2] );
452                     }
453                     for ( i = 0; i < vncount; ++i ) {
454                         sgSetVec3( vnlist[i], 
455                                    normals[i][0], 
456                                    normals[i][1],
457                                    normals[i][2] );
458                     }
459                     for ( i = 0; i < vtcount; ++i ) {
460                         sgSetVec2( tclist[i],
461                                    tex_coords[i][0],
462                                    tex_coords[i][1] );
463                     }
464                 }
465
466                 // display_list = xglGenLists(1);
467                 // xglNewList(display_list, GL_COMPILE);
468                 // printf("xglGenLists(); xglNewList();\n");
469                 in_faces = false;
470
471                 // scan the material line
472                 in >> material;
473                 
474                 // find this material in the properties list
475
476                 newmat = material_lib.find( material );
477                 if ( newmat == NULL ) {
478                     // see if this is an on the fly texture
479                     string file = path;
480                     int pos = file.rfind( "/" );
481                     file = file.substr( 0, pos );
482                     cout << "current file = " << file << endl;
483                     file += "/";
484                     file += material;
485                     cout << "current file = " << file << endl;
486                     if ( ! material_lib.add_item( file ) ) {
487                         SG_LOG( SG_TERRAIN, SG_ALERT, 
488                                 "Ack! unknown usemtl name = " << material 
489                                 << " in " << path );
490                     } else {
491                         // locate our newly created material
492                         newmat = material_lib.find( material );
493                         if ( newmat == NULL ) {
494                             SG_LOG( SG_TERRAIN, SG_ALERT, 
495                                     "Ack! bad on the fly materia create = "
496                                     << material << " in " << path );
497                         }
498                     }
499                 }
500
501                 if ( newmat != NULL ) {
502                     // set the texture width and height values for this
503                     // material
504                     tex_width = newmat->get_xsize();
505                     tex_height = newmat->get_ysize();
506                     state = newmat->get_state();
507                     coverage = newmat->get_light_coverage();
508                     // cout << "(w) = " << tex_width << " (h) = " 
509                     //      << tex_width << endl;
510                 } else {
511                     coverage = -1;
512                 }
513             } else {
514                 // unknown comment, just gobble the input until the
515                 // end of line
516
517                 in >> skipeol;
518             }
519         } else {
520             in.putback( c );
521         
522             in >> token;
523
524             // cout << "token = " << token << endl;
525
526             if ( token == "vn" ) {
527                 // vertex normal
528                 if ( vncount < FG_MAX_NODES ) {
529                     in >> normals[vncount][0]
530                        >> normals[vncount][1]
531                        >> normals[vncount][2];
532                     vncount++;
533                 } else {
534                     SG_LOG( SG_TERRAIN, SG_ALERT, 
535                             "Read too many vertex normals in " << path 
536                             << " ... dying :-(" );
537                     exit(-1);
538                 }
539             } else if ( token == "vt" ) {
540                 // vertex texture coordinate
541                 if ( vtcount < FG_MAX_NODES*3 ) {
542                     in >> tex_coords[vtcount][0]
543                        >> tex_coords[vtcount][1];
544                     vtcount++;
545                 } else {
546                     SG_LOG( SG_TERRAIN, SG_ALERT, 
547                             "Read too many vertex texture coords in " << path
548                             << " ... dying :-("
549                             );
550                     exit(-1);
551                 }
552             } else if ( token == "v" ) {
553                 // node (vertex)
554                 if ( t->ncount < FG_MAX_NODES ) {
555                     /* in >> nodes[t->ncount][0]
556                        >> nodes[t->ncount][1]
557                        >> nodes[t->ncount][2]; */
558                     in >> node;
559                     nodes.push_back(node);
560                     if ( is_base ) {
561                         t->ncount++;
562                     }
563                 } else {
564                     SG_LOG( SG_TERRAIN, SG_ALERT, 
565                             "Read too many nodes in " << path 
566                             << " ... dying :-(");
567                     exit(-1);
568                 }
569             } else if ( (token == "tf") || (token == "ts") || (token == "f") ) {
570                 // triangle fan, strip, or individual face
571                 // SG_LOG( SG_TERRAIN, SG_INFO, "new fan or strip");
572
573                 fan_vertices.clear();
574                 fan_tex_coords.clear();
575                 odd = true;
576
577                 // xglBegin(GL_TRIANGLE_FAN);
578
579                 in >> n1;
580                 fan_vertices.push_back( n1 );
581                 // xglNormal3dv(normals[n1]);
582                 if ( in.get( c ) && c == '/' ) {
583                     in >> tex;
584                     fan_tex_coords.push_back( tex );
585                     if ( scenery_version >= 0.4 ) {
586                         if ( tex_width > 0 ) {
587                             tclist[tex][0] *= (1000.0 / tex_width);
588                         }
589                         if ( tex_height > 0 ) {
590                             tclist[tex][1] *= (1000.0 / tex_height);
591                         }
592                     }
593                     pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
594                     pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
595                 } else {
596                     in.putback( c );
597                     pp = local_calc_tex_coords(nodes[n1], center);
598                 }
599                 // xglTexCoord2f(pp.x(), pp.y());
600                 // xglVertex3dv(nodes[n1].get_n());
601
602                 in >> n2;
603                 fan_vertices.push_back( n2 );
604                 // xglNormal3dv(normals[n2]);
605                 if ( in.get( c ) && c == '/' ) {
606                     in >> tex;
607                     fan_tex_coords.push_back( tex );
608                     if ( scenery_version >= 0.4 ) {
609                         if ( tex_width > 0 ) {
610                             tclist[tex][0] *= (1000.0 / tex_width);
611                         }
612                         if ( tex_height > 0 ) {
613                             tclist[tex][1] *= (1000.0 / tex_height);
614                         }
615                     }
616                     pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
617                     pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
618                 } else {
619                     in.putback( c );
620                     pp = local_calc_tex_coords(nodes[n2], center);
621                 }
622                 // xglTexCoord2f(pp.x(), pp.y());
623                 // xglVertex3dv(nodes[n2].get_n());
624                 
625                 // read all subsequent numbers until next thing isn't a number
626                 while ( true ) {
627                     in >> ::skipws;
628
629                     char c;
630                     in.get(c);
631                     in.putback(c);
632                     if ( ! isdigit(c) || in.eof() ) {
633                         break;
634                     }
635
636                     in >> n3;
637                     fan_vertices.push_back( n3 );
638                     // cout << "  triangle = " 
639                     //      << n1 << "," << n2 << "," << n3 
640                     //      << endl;
641                     // xglNormal3dv(normals[n3]);
642                     if ( in.get( c ) && c == '/' ) {
643                         in >> tex;
644                         fan_tex_coords.push_back( tex );
645                         if ( scenery_version >= 0.4 ) {
646                             if ( tex_width > 0 ) {
647                                 tclist[tex][0] *= (1000.0 / tex_width);
648                             }
649                             if ( tex_height > 0 ) {
650                                 tclist[tex][1] *= (1000.0 / tex_height);
651                             }
652                         }
653                         pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
654                         pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
655                     } else {
656                         in.putback( c );
657                         pp = local_calc_tex_coords(nodes[n3], center);
658                     }
659                     // xglTexCoord2f(pp.x(), pp.y());
660                     // xglVertex3dv(nodes[n3].get_n());
661
662                     if ( (token == "tf") || (token == "f") ) {
663                         // triangle fan
664                         n2 = n3;
665                     } else {
666                         // triangle strip
667                         odd = !odd;
668                         n1 = n2;
669                         n2 = n3;
670                     }
671                 }
672
673                 // xglEnd();
674
675                 // build the ssg entity
676                 int size = (int)fan_vertices.size();
677                 ssgVertexArray   *vl = new ssgVertexArray( size );
678                 ssgNormalArray   *nl = new ssgNormalArray( size );
679                 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
680                 ssgColourArray   *cl = new ssgColourArray( 1 );
681
682                 sgVec4 color;
683                 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
684                 cl->add( color );
685
686                 sgVec2 tmp2;
687                 sgVec3 tmp3;
688                 for ( i = 0; i < size; ++i ) {
689                     sgCopyVec3( tmp3, vtlist[ fan_vertices[i] ] );
690                     vl -> add( tmp3 );
691
692                     sgCopyVec3( tmp3, vnlist[ fan_vertices[i] ] );
693                     nl -> add( tmp3 );
694
695                     sgCopyVec2( tmp2, tclist[ fan_tex_coords[i] ] );
696                     tl -> add( tmp2 );
697                 }
698
699                 ssgLeaf *leaf = NULL;
700                 if ( token == "tf" ) {
701                     // triangle fan
702                     leaf = 
703                         new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
704                 } else if ( token == "ts" ) {
705                     // triangle strip
706                     leaf = 
707                         new ssgVtxTable ( GL_TRIANGLE_STRIP, vl, nl, tl, cl );
708                 } else if ( token == "f" ) {
709                     // triangle
710                     leaf = 
711                         new ssgVtxTable ( GL_TRIANGLES, vl, nl, tl, cl );
712                 }
713                 // leaf->makeDList();
714                 leaf->setState( state );
715
716                 tile->addKid( leaf );
717
718                 if ( is_base ) {
719                     if ( coverage > 0.0 ) {
720                         if ( coverage < 10000.0 ) {
721                             SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
722                                    << coverage << ", pushing up to 10000");
723                             coverage = 10000;
724                         }
725                         gen_random_surface_points(leaf, lights, coverage);
726                     }
727                 }
728             } else {
729                 SG_LOG( SG_TERRAIN, SG_WARN, "Unknown token in " 
730                         << path << " = " << token );
731             }
732
733             // eat white space before start of while loop so if we are
734             // done with useful input it is noticed before hand.
735             in >> ::skipws;
736         }
737     }
738
739     if ( is_base ) {
740         t->nodes = nodes;
741     }
742
743     stopwatch.stop();
744     SG_LOG( SG_TERRAIN, SG_DEBUG, 
745             "Loaded " << path << " in " 
746             << stopwatch.elapsedSeconds() << " seconds" );
747
748     return tile;
749 }
750
751
752 ssgLeaf *gen_leaf( const string& path,
753                    const GLenum ty, const string& material,
754                    const point_list& nodes, const point_list& normals,
755                    const point_list& texcoords,
756                    const int_list node_index,
757                    const int_list& tex_index,
758                    const bool calc_lights, ssgVertexArray *lights )
759 {
760     double tex_width = 1000.0, tex_height = 1000.0;
761     ssgSimpleState *state = NULL;
762     float coverage = -1;
763
764     FGNewMat *newmat = material_lib.find( material );
765     if ( newmat == NULL ) {
766         // see if this is an on the fly texture
767         string file = path;
768         int pos = file.rfind( "/" );
769         file = file.substr( 0, pos );
770         cout << "current file = " << file << endl;
771         file += "/";
772         file += material;
773         cout << "current file = " << file << endl;
774         if ( ! material_lib.add_item( file ) ) {
775             SG_LOG( SG_TERRAIN, SG_ALERT, 
776                     "Ack! unknown usemtl name = " << material 
777                     << " in " << path );
778         } else {
779             // locate our newly created material
780             newmat = material_lib.find( material );
781             if ( newmat == NULL ) {
782                 SG_LOG( SG_TERRAIN, SG_ALERT, 
783                         "Ack! bad on the fly material create = "
784                         << material << " in " << path );
785             }
786         }
787     }
788
789     if ( newmat != NULL ) {
790         // set the texture width and height values for this
791         // material
792         tex_width = newmat->get_xsize();
793         tex_height = newmat->get_ysize();
794         state = newmat->get_state();
795         coverage = newmat->get_light_coverage();
796         // cout << "(w) = " << tex_width << " (h) = " 
797         //      << tex_width << endl;
798     } else {
799         coverage = -1;
800     }
801
802     // cout << "before list allocs" << endl;
803
804     int size = node_index.size();
805
806     if ( size < 1 ) {
807         SG_LOG( SG_TERRAIN, SG_ALERT, "Woh! list size < 1" );
808         exit(-1);
809     }
810
811     // cout << "before vl, size = " << size << endl;
812     ssgVertexArray   *vl = new ssgVertexArray( size );
813     // cout << "before nl" << endl;
814     ssgNormalArray   *nl = new ssgNormalArray( size );
815     // cout << "before tl" << endl;
816     ssgTexCoordArray *tl = new ssgTexCoordArray( size );
817     // cout << "before cl" << endl;
818     ssgColourArray   *cl = new ssgColourArray( 1 );
819
820     sgVec4 color;
821     sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
822     cl->add( color );
823
824     sgVec2 tmp2;
825     sgVec3 tmp3;
826     int i;
827     for ( i = 0; i < size; ++i ) {
828         Point3D node = nodes[ node_index[i] ];
829         sgSetVec3( tmp3, node[0], node[1], node[2] );
830         vl -> add( tmp3 );
831
832         Point3D normal = normals[ node_index[i] ];
833         sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
834         nl -> add( tmp3 );
835
836         Point3D texcoord = texcoords[ tex_index[i] ];
837         sgSetVec2( tmp2, texcoord[0], texcoord[1] );
838         if ( tex_width > 0 ) {
839             tmp2[0] *= (1000.0 / tex_width);
840         }
841         if ( tex_height > 0 ) {
842             tmp2[1] *= (1000.0 / tex_height);
843         }
844         tl -> add( tmp2 );
845     }
846
847     // cout << "before leaf create" << endl;
848     ssgLeaf *leaf = new ssgVtxTable ( ty, vl, nl, tl, cl );
849     // cout << "after leaf create" << endl;
850
851     // lookup the state record
852     // cout << "looking up material = " << endl;
853     // cout << material << endl;
854     // cout << "'" << endl;
855
856     leaf->setState( state );
857
858     if ( calc_lights ) {
859         if ( coverage > 0.0 ) {
860             if ( coverage < 10000.0 ) {
861                 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
862                        << coverage << ", pushing up to 10000");
863                 coverage = 10000;
864             }
865             gen_random_surface_points(leaf, lights, coverage);
866         }
867     }
868
869     return leaf;
870 }
871
872
873 // Load an Binary obj file
874 ssgBranch *fgBinObjLoad( const string& path, FGTileEntry *t,
875                          ssgVertexArray *lights, const bool is_base)
876 {
877     int i;
878
879     SGBinObject obj;
880     bool result = obj.read_bin( path );
881
882     if ( !result ) {
883         return NULL;
884     }
885
886     // cout << "fans size = " << obj.get_fans_v().size()
887     //      << " fan_mats size = " << obj.get_fan_materials().size() << endl;
888
889     ssgBranch *object = new ssgBranch();
890     object->setName( (char *)path.c_str() );
891    
892     if ( is_base && t != NULL ) {
893         // reference point (center offset/bounding sphere)
894         t->center = obj.get_gbs_center();
895         t->bounding_radius = obj.get_gbs_radius();
896     }
897
898     point_list nodes = obj.get_wgs84_nodes();
899     point_list normals = obj.get_normals();
900     point_list texcoords = obj.get_texcoords();
901
902     string material;
903     int_list vertex_index;
904     int_list tex_index;
905
906     // generate triangles
907     string_list tri_materials = obj.get_tri_materials();
908     group_list tris_v = obj.get_tris_v();
909     group_list tris_tc = obj.get_tris_tc();
910     for ( i = 0; i < (int)tris_v.size(); ++i ) {
911         material = tri_materials[i];
912         vertex_index = tris_v[i];
913         tex_index = tris_tc[i];
914         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLES, material,
915                                   nodes, normals, texcoords,
916                                   vertex_index, tex_index,
917                                   is_base, lights );
918
919         object->addKid( leaf );
920     }
921
922     // generate strips
923     string_list strip_materials = obj.get_strip_materials();
924     group_list strips_v = obj.get_strips_v();
925     group_list strips_tc = obj.get_strips_tc();
926     for ( i = 0; i < (int)strips_v.size(); ++i ) {
927         material = strip_materials[i];
928         vertex_index = strips_v[i];
929         tex_index = strips_tc[i];
930         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_STRIP, material,
931                                   nodes, normals, texcoords,
932                                   vertex_index, tex_index,
933                                   is_base, lights );
934
935         object->addKid( leaf );
936     }
937
938     // generate fans
939     string_list fan_materials = obj.get_fan_materials();
940     group_list fans_v = obj.get_fans_v();
941     group_list fans_tc = obj.get_fans_tc();
942     for ( i = 0; i < (int)fans_v.size(); ++i ) {
943         material = fan_materials[i];
944         vertex_index = fans_v[i];
945         tex_index = fans_tc[i];
946         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_FAN, material,
947                                   nodes, normals, texcoords,
948                                   vertex_index, tex_index,
949                                   is_base, lights );
950
951         object->addKid( leaf );
952     }
953
954     return object;
955 }