]> git.mxchange.org Git - flightgear.git/blob - src/Objects/obj.cxx
Replaced some debugging structure David inadvertantly removed.
[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 an ocean tile
112 bool fgGenTile( const string& path, SGBucket b,
113                       Point3D *center,
114                       double *bounding_radius,
115                       ssgBranch* geometry )
116 {
117     FGNewMat *newmat;
118
119     ssgSimpleState *state = NULL;
120
121     geometry -> setName ( (char *)path.c_str() ) ;
122
123     double tex_width = 1000.0;
124     // double tex_height;
125
126     // find Ocean material in the properties list
127     newmat = material_lib.find( "Ocean" );
128     if ( newmat != NULL ) {
129         // set the texture width and height values for this
130         // material
131         tex_width = newmat->get_xsize();
132         // tex_height = newmat->get_ysize();
133         
134         // set ssgState
135         state = newmat->get_state();
136     } else {
137         SG_LOG( SG_TERRAIN, SG_ALERT, 
138                 "Ack! unknown usemtl name = " << "Ocean" 
139                 << " in " << path );
140     }
141
142     // Calculate center point
143     double clon = b.get_center_lon();
144     double clat = b.get_center_lat();
145     double height = b.get_height();
146     double width = b.get_width();
147
148     *center = sgGeodToCart( Point3D(clon*SGD_DEGREES_TO_RADIANS,
149                                     clat*SGD_DEGREES_TO_RADIANS,
150                                     0.0) );
151     // cout << "center = " << center << endl;;
152     
153     // Caculate corner vertices
154     Point3D geod[4];
155     geod[0] = Point3D( clon - width/2.0, clat - height/2.0, 0.0 );
156     geod[1] = Point3D( clon + width/2.0, clat - height/2.0, 0.0 );
157     geod[2] = Point3D( clon + width/2.0, clat + height/2.0, 0.0 );
158     geod[3] = Point3D( clon - width/2.0, clat + height/2.0, 0.0 );
159
160     Point3D rad[4];
161     int i;
162     for ( i = 0; i < 4; ++i ) {
163         rad[i] = Point3D( geod[i].x() * SGD_DEGREES_TO_RADIANS,
164                           geod[i].y() * SGD_DEGREES_TO_RADIANS,
165                           geod[i].z() );
166     }
167
168     Point3D cart[4], rel[4];
169     for ( i = 0; i < 4; ++i ) {
170         cart[i] = sgGeodToCart(rad[i]);
171         rel[i] = cart[i] - *center;
172         // cout << "corner " << i << " = " << cart[i] << endl;
173     }
174
175     // Calculate bounding radius
176     *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         double length = cart[i].distance3D( Point3D(0.0) );
183         normals[i] = cart[i] / length;
184         // cout << "normal = " << normals[i] << endl;
185     }
186
187     // Calculate texture coordinates
188     point_list geod_nodes;
189     geod_nodes.clear();
190     int_list rectangle;
191     rectangle.clear();
192     for ( i = 0; i < 4; ++i ) {
193         geod_nodes.push_back( geod[i] );
194         rectangle.push_back( i );
195     }
196     point_list texs = calc_tex_coords( b, geod_nodes, rectangle, 
197                                        1000.0 / tex_width );
198
199     // Allocate ssg structure
200     ssgVertexArray   *vl = new ssgVertexArray( 4 );
201     ssgNormalArray   *nl = new ssgNormalArray( 4 );
202     ssgTexCoordArray *tl = new ssgTexCoordArray( 4 );
203     ssgColourArray   *cl = new ssgColourArray( 1 );
204
205     sgVec4 color;
206     sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
207     cl->add( color );
208
209     // sgVec3 *vtlist = new sgVec3 [ 4 ];
210     // t->vec3_ptrs.push_back( vtlist );
211     // sgVec3 *vnlist = new sgVec3 [ 4 ];
212     // t->vec3_ptrs.push_back( vnlist );
213     // sgVec2 *tclist = new sgVec2 [ 4 ];
214     // t->vec2_ptrs.push_back( tclist );
215
216     sgVec2 tmp2;
217     sgVec3 tmp3;
218     for ( i = 0; i < 4; ++i ) {
219         sgSetVec3( tmp3, 
220                    rel[i].x(), rel[i].y(), rel[i].z() );
221         vl->add( tmp3 );
222
223         sgSetVec3( tmp3, 
224                    normals[i].x(), normals[i].y(), normals[i].z() );
225         nl->add( tmp3 );
226
227         sgSetVec2( tmp2, texs[i].x(), texs[i].y());
228         tl->add( tmp2 );
229     }
230     
231     ssgLeaf *leaf = 
232         new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
233
234     leaf->setState( state );
235
236     geometry->addKid( leaf );
237
238     return true;
239 }
240
241
242 static void random_pt_inside_tri( float *res,
243                                   float *n1, float *n2, float *n3 )
244 {
245     sgVec3 p1, p2, p3;
246
247     double a = sg_random();
248     double b = sg_random();
249     if ( a + b > 1.0 ) {
250         a = 1.0 - a;
251         b = 1.0 - b;
252     }
253     double c = 1 - a - b;
254
255     sgScaleVec3( p1, n1, a );
256     sgScaleVec3( p2, n2, b );
257     sgScaleVec3( p3, n3, c );
258
259     sgAddVec3( res, p1, p2 );
260     sgAddVec3( res, p3 );
261 }
262
263
264 static void gen_random_surface_points( ssgLeaf *leaf, ssgVertexArray *lights,
265                                        double factor ) {
266     int num = leaf->getNumTriangles();
267     if ( num > 0 ) {
268         short int n1, n2, n3;
269         float *p1, *p2, *p3;
270         sgVec3 result;
271
272         // generate a repeatable random seed
273         p1 = leaf->getVertex( 0 );
274         unsigned int seed = (unsigned int)p1[0];
275         sg_srandom( seed );
276
277         for ( int i = 0; i < num; ++i ) {
278             leaf->getTriangle( i, &n1, &n2, &n3 );
279             p1 = leaf->getVertex(n1);
280             p2 = leaf->getVertex(n2);
281             p3 = leaf->getVertex(n3);
282             double area = sgTriArea( p1, p2, p3 );
283             double num = area / factor;
284
285             // generate a light point for each unit of area
286             while ( num > 1.0 ) {
287                 random_pt_inside_tri( result, p1, p2, p3 );
288                 lights->add( result );
289                 num -= 1.0;
290             }
291             // for partial units of area, use a zombie door method to
292             // create the proper random chance of a light being created
293             // for this triangle
294             if ( num > 0.0 ) {
295                 if ( sg_random() <= num ) {
296                     // a zombie made it through our door
297                     random_pt_inside_tri( result, p1, p2, p3 );
298                     lights->add( result );
299                 }
300             }
301         }
302     }
303 }
304
305
306 // Load an Ascii obj file
307 ssgBranch *fgAsciiObjLoad( const string& path, FGTileEntry *t,
308                            ssgVertexArray *lights, const bool is_base)
309 {
310     FGNewMat *newmat = NULL;
311     string material;
312     float coverage = -1;
313     Point3D pp;
314     // sgVec3 approx_normal;
315     // double normal[3], scale = 0.0;
316     // double x, y, z, xmax, xmin, ymax, ymin, zmax, zmin;
317     // GLfloat sgenparams[] = { 1.0, 0.0, 0.0, 0.0 };
318     // GLint display_list = 0;
319     int shading;
320     bool in_faces = false;
321     int vncount, vtcount;
322     int n1 = 0, n2 = 0, n3 = 0;
323     int tex;
324     // int last1 = 0, last2 = 0;
325     bool odd = false;
326     point_list nodes;
327     Point3D node;
328     Point3D center;
329     double scenery_version = 0.0;
330     double tex_width = 1000.0, tex_height = 1000.0;
331     bool shared_done = false;
332     int_list fan_vertices;
333     int_list fan_tex_coords;
334     int i;
335     ssgSimpleState *state = NULL;
336     sgVec3 *vtlist, *vnlist;
337     sgVec2 *tclist;
338
339     ssgBranch *tile = new ssgBranch () ;
340
341     tile -> setName ( (char *)path.c_str() ) ;
342
343     // Attempt to open "path.gz" or "path"
344     sg_gzifstream in( path );
345     if ( ! in.is_open() ) {
346         SG_LOG( SG_TERRAIN, SG_DEBUG, "Cannot open file: " << path );
347         SG_LOG( SG_TERRAIN, SG_DEBUG, "default to ocean tile: " << path );
348
349         delete tile;
350
351         return NULL;
352     }
353
354     shading = fgGetBool("/sim/rendering/shading");
355
356     if ( is_base ) {
357         t->ncount = 0;
358     }
359     vncount = 0;
360     vtcount = 0;
361     if ( is_base ) {
362         t->bounding_radius = 0.0;
363     }
364     center = t->center;
365
366     // StopWatch stopwatch;
367     // stopwatch.start();
368
369     // ignore initial comments and blank lines. (priming the pump)
370     // in >> skipcomment;
371     // string line;
372
373     string token;
374     char c;
375
376 #ifdef __MWERKS__
377     while ( in.get(c) && c  != '\0' ) {
378         in.putback(c);
379 #else
380     while ( ! in.eof() ) {
381 #endif
382
383         in >> ::skipws;
384
385         if ( in.get( c ) && c == '#' ) {
386             // process a comment line
387
388             // getline( in, line );
389             // cout << "comment = " << line << endl;
390
391             in >> token;
392
393             if ( token == "Version" ) {
394                 // read scenery versions number
395                 in >> scenery_version;
396                 // cout << "scenery_version = " << scenery_version << endl;
397                 if ( scenery_version > 0.4 ) {
398                     SG_LOG( SG_TERRAIN, SG_ALERT, 
399                             "\nYou are attempting to load a tile format that\n"
400                             << "is newer than this version of flightgear can\n"
401                             << "handle.  You should upgrade your copy of\n"
402                             << "FlightGear to the newest version.  For\n"
403                             << "details, please see:\n"
404                             << "\n    http://www.flightgear.org\n" );
405                     exit(-1);
406                 }
407             } else if ( token == "gbs" ) {
408                 // reference point (center offset)
409                 if ( is_base ) {
410                     in >> t->center >> t->bounding_radius;
411                 } else {
412                     Point3D junk1;
413                     double junk2;
414                     in >> junk1 >> junk2;
415                 }
416                 center = t->center;
417                 // cout << "center = " << center 
418                 //      << " radius = " << t->bounding_radius << endl;
419             } else if ( token == "bs" ) {
420                 // reference point (center offset)
421                 // (skip past this)
422                 Point3D junk1;
423                 double junk2;
424                 in >> junk1 >> junk2;
425             } else if ( token == "usemtl" ) {
426                 // material property specification
427
428                 // if first usemtl with shared_done = false, then set
429                 // shared_done true and build the ssg shared lists
430                 if ( ! shared_done ) {
431                     // sanity check
432                     if ( (int)nodes.size() != vncount ) {
433                         SG_LOG( SG_TERRAIN, SG_ALERT, 
434                                 "Tile has mismatched nodes = " << nodes.size()
435                                 << " and normals = " << vncount << " : " 
436                                 << path );
437                         // exit(-1);
438                     }
439                     shared_done = true;
440
441                     vtlist = new sgVec3 [ nodes.size() ];
442                     t->vec3_ptrs.push_back( vtlist );
443                     vnlist = new sgVec3 [ vncount ];
444                     t->vec3_ptrs.push_back( vnlist );
445                     tclist = new sgVec2 [ vtcount ];
446                     t->vec2_ptrs.push_back( tclist );
447
448                     for ( i = 0; i < (int)nodes.size(); ++i ) {
449                         sgSetVec3( vtlist[i], 
450                                    nodes[i][0], nodes[i][1], nodes[i][2] );
451                     }
452                     for ( i = 0; i < vncount; ++i ) {
453                         sgSetVec3( vnlist[i], 
454                                    normals[i][0], 
455                                    normals[i][1],
456                                    normals[i][2] );
457                     }
458                     for ( i = 0; i < vtcount; ++i ) {
459                         sgSetVec2( tclist[i],
460                                    tex_coords[i][0],
461                                    tex_coords[i][1] );
462                     }
463                 }
464
465                 // display_list = xglGenLists(1);
466                 // xglNewList(display_list, GL_COMPILE);
467                 // printf("xglGenLists(); xglNewList();\n");
468                 in_faces = false;
469
470                 // scan the material line
471                 in >> material;
472                 
473                 // find this material in the properties list
474
475                 newmat = material_lib.find( material );
476                 if ( newmat == NULL ) {
477                     // see if this is an on the fly texture
478                     string file = path;
479                     int pos = file.rfind( "/" );
480                     file = file.substr( 0, pos );
481                     // cout << "current file = " << file << endl;
482                     file += "/";
483                     file += material;
484                     // cout << "current file = " << file << endl;
485                     if ( ! material_lib.add_item( file ) ) {
486                         SG_LOG( SG_TERRAIN, SG_ALERT, 
487                                 "Ack! unknown usemtl name = " << material 
488                                 << " in " << path );
489                     } else {
490                         // locate our newly created material
491                         newmat = material_lib.find( material );
492                         if ( newmat == NULL ) {
493                             SG_LOG( SG_TERRAIN, SG_ALERT, 
494                                     "Ack! bad on the fly materia create = "
495                                     << material << " in " << path );
496                         }
497                     }
498                 }
499
500                 if ( newmat != NULL ) {
501                     // set the texture width and height values for this
502                     // material
503                     tex_width = newmat->get_xsize();
504                     tex_height = newmat->get_ysize();
505                     state = newmat->get_state();
506                     coverage = newmat->get_light_coverage();
507                     // cout << "(w) = " << tex_width << " (h) = "
508                     //      << tex_width << endl;
509                 } else {
510                     coverage = -1;
511                 }
512             } else {
513                 // unknown comment, just gobble the input until the
514                 // end of line
515
516                 in >> skipeol;
517             }
518         } else {
519             in.putback( c );
520         
521             in >> token;
522
523             // cout << "token = " << token << endl;
524
525             if ( token == "vn" ) {
526                 // vertex normal
527                 if ( vncount < FG_MAX_NODES ) {
528                     in >> normals[vncount][0]
529                        >> normals[vncount][1]
530                        >> normals[vncount][2];
531                     vncount++;
532                 } else {
533                     SG_LOG( SG_TERRAIN, SG_ALERT, 
534                             "Read too many vertex normals in " << path 
535                             << " ... dying :-(" );
536                     exit(-1);
537                 }
538             } else if ( token == "vt" ) {
539                 // vertex texture coordinate
540                 if ( vtcount < FG_MAX_NODES*3 ) {
541                     in >> tex_coords[vtcount][0]
542                        >> tex_coords[vtcount][1];
543                     vtcount++;
544                 } else {
545                     SG_LOG( SG_TERRAIN, SG_ALERT, 
546                             "Read too many vertex texture coords in " << path
547                             << " ... dying :-("
548                             );
549                     exit(-1);
550                 }
551             } else if ( token == "v" ) {
552                 // node (vertex)
553                 if ( t->ncount < FG_MAX_NODES ) {
554                     /* in >> nodes[t->ncount][0]
555                        >> nodes[t->ncount][1]
556                        >> nodes[t->ncount][2]; */
557                     in >> node;
558                     nodes.push_back(node);
559                     if ( is_base ) {
560                         t->ncount++;
561                     }
562                 } else {
563                     SG_LOG( SG_TERRAIN, SG_ALERT, 
564                             "Read too many nodes in " << path 
565                             << " ... dying :-(");
566                     exit(-1);
567                 }
568             } else if ( (token == "tf") || (token == "ts") || (token == "f") ) {
569                 // triangle fan, strip, or individual face
570                 // SG_LOG( SG_TERRAIN, SG_INFO, "new fan or strip");
571
572                 fan_vertices.clear();
573                 fan_tex_coords.clear();
574                 odd = true;
575
576                 // xglBegin(GL_TRIANGLE_FAN);
577
578                 in >> n1;
579                 fan_vertices.push_back( n1 );
580                 // xglNormal3dv(normals[n1]);
581                 if ( in.get( c ) && c == '/' ) {
582                     in >> tex;
583                     fan_tex_coords.push_back( tex );
584                     if ( scenery_version >= 0.4 ) {
585                         if ( tex_width > 0 ) {
586                             tclist[tex][0] *= (1000.0 / tex_width);
587                         }
588                         if ( tex_height > 0 ) {
589                             tclist[tex][1] *= (1000.0 / tex_height);
590                         }
591                     }
592                     pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
593                     pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
594                 } else {
595                     in.putback( c );
596                     pp = local_calc_tex_coords(nodes[n1], center);
597                 }
598                 // xglTexCoord2f(pp.x(), pp.y());
599                 // xglVertex3dv(nodes[n1].get_n());
600
601                 in >> n2;
602                 fan_vertices.push_back( n2 );
603                 // xglNormal3dv(normals[n2]);
604                 if ( in.get( c ) && c == '/' ) {
605                     in >> tex;
606                     fan_tex_coords.push_back( tex );
607                     if ( scenery_version >= 0.4 ) {
608                         if ( tex_width > 0 ) {
609                             tclist[tex][0] *= (1000.0 / tex_width);
610                         }
611                         if ( tex_height > 0 ) {
612                             tclist[tex][1] *= (1000.0 / tex_height);
613                         }
614                     }
615                     pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
616                     pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
617                 } else {
618                     in.putback( c );
619                     pp = local_calc_tex_coords(nodes[n2], center);
620                 }
621                 // xglTexCoord2f(pp.x(), pp.y());
622                 // xglVertex3dv(nodes[n2].get_n());
623                 
624                 // read all subsequent numbers until next thing isn't a number
625                 while ( true ) {
626                     in >> ::skipws;
627
628                     char c;
629                     in.get(c);
630                     in.putback(c);
631                     if ( ! isdigit(c) || in.eof() ) {
632                         break;
633                     }
634
635                     in >> n3;
636                     fan_vertices.push_back( n3 );
637                     // cout << "  triangle = "
638                     //      << n1 << "," << n2 << "," << n3
639                     //      << endl;
640                     // xglNormal3dv(normals[n3]);
641                     if ( in.get( c ) && c == '/' ) {
642                         in >> tex;
643                         fan_tex_coords.push_back( tex );
644                         if ( scenery_version >= 0.4 ) {
645                             if ( tex_width > 0 ) {
646                                 tclist[tex][0] *= (1000.0 / tex_width);
647                             }
648                             if ( tex_height > 0 ) {
649                                 tclist[tex][1] *= (1000.0 / tex_height);
650                             }
651                         }
652                         pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
653                         pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
654                     } else {
655                         in.putback( c );
656                         pp = local_calc_tex_coords(nodes[n3], center);
657                     }
658                     // xglTexCoord2f(pp.x(), pp.y());
659                     // xglVertex3dv(nodes[n3].get_n());
660
661                     if ( (token == "tf") || (token == "f") ) {
662                         // triangle fan
663                         n2 = n3;
664                     } else {
665                         // triangle strip
666                         odd = !odd;
667                         n1 = n2;
668                         n2 = n3;
669                     }
670                 }
671
672                 // xglEnd();
673
674                 // build the ssg entity
675                 int size = (int)fan_vertices.size();
676                 ssgVertexArray   *vl = new ssgVertexArray( size );
677                 ssgNormalArray   *nl = new ssgNormalArray( size );
678                 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
679                 ssgColourArray   *cl = new ssgColourArray( 1 );
680
681                 sgVec4 color;
682                 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
683                 cl->add( color );
684
685                 sgVec2 tmp2;
686                 sgVec3 tmp3;
687                 for ( i = 0; i < size; ++i ) {
688                     sgCopyVec3( tmp3, vtlist[ fan_vertices[i] ] );
689                     vl -> add( tmp3 );
690
691                     sgCopyVec3( tmp3, vnlist[ fan_vertices[i] ] );
692                     nl -> add( tmp3 );
693
694                     sgCopyVec2( tmp2, tclist[ fan_tex_coords[i] ] );
695                     tl -> add( tmp2 );
696                 }
697
698                 ssgLeaf *leaf = NULL;
699                 if ( token == "tf" ) {
700                     // triangle fan
701                     leaf = 
702                         new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
703                 } else if ( token == "ts" ) {
704                     // triangle strip
705                     leaf = 
706                         new ssgVtxTable ( GL_TRIANGLE_STRIP, vl, nl, tl, cl );
707                 } else if ( token == "f" ) {
708                     // triangle
709                     leaf = 
710                         new ssgVtxTable ( GL_TRIANGLES, vl, nl, tl, cl );
711                 }
712                 // leaf->makeDList();
713                 leaf->setState( state );
714
715                 tile->addKid( leaf );
716
717                 if ( is_base ) {
718                     if ( coverage > 0.0 ) {
719                         if ( coverage < 10000.0 ) {
720                             SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
721                                    << coverage << ", pushing up to 10000");
722                             coverage = 10000;
723                         }
724                         gen_random_surface_points(leaf, lights, coverage);
725                     }
726                 }
727             } else {
728                 SG_LOG( SG_TERRAIN, SG_WARN, "Unknown token in " 
729                         << path << " = " << token );
730             }
731
732             // eat white space before start of while loop so if we are
733             // done with useful input it is noticed before hand.
734             in >> ::skipws;
735         }
736     }
737
738     if ( is_base ) {
739         t->nodes = nodes;
740     }
741
742     // stopwatch.stop();
743     // SG_LOG( SG_TERRAIN, SG_DEBUG, 
744     //     "Loaded " << path << " in " 
745     //     << stopwatch.elapsedSeconds() << " seconds" );
746
747     return tile;
748 }
749
750
751 ssgLeaf *gen_leaf( const string& path,
752                    const GLenum ty, const string& material,
753                    const point_list& nodes, const point_list& normals,
754                    const point_list& texcoords,
755                    const int_list node_index,
756                    const int_list normal_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     sgVec2 tmp2;
803     sgVec3 tmp3;
804     sgVec4 tmp4;
805     int i;
806
807     // vertices
808     int size = node_index.size();
809     if ( size < 1 ) {
810         SG_LOG( SG_TERRAIN, SG_ALERT, "Woh! node list size < 1" );
811         exit(-1);
812     }
813     ssgVertexArray *vl = new ssgVertexArray( size );
814     Point3D node;
815     for ( i = 0; i < size; ++i ) {
816         node = nodes[ node_index[i] ];
817         sgSetVec3( tmp3, node[0], node[1], node[2] );
818         vl -> add( tmp3 );
819     }
820
821     // normals
822     Point3D normal;
823     ssgNormalArray *nl = new ssgNormalArray( size );
824     if ( normal_index.size() ) {
825         // object file specifies normal indices (i.e. normal indices
826         // aren't 'implied'
827         for ( i = 0; i < size; ++i ) {
828             normal = normals[ normal_index[i] ];
829             sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
830             nl -> add( tmp3 );
831         }
832     } else {
833         // use implied normal indices.  normal index = vertex index.
834         for ( i = 0; i < size; ++i ) {
835             normal = normals[ node_index[i] ];
836             sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
837             nl -> add( tmp3 );
838         }
839     }
840
841     // colors
842     ssgColourArray *cl = new ssgColourArray( 1 );
843     sgSetVec4( tmp4, 1.0, 1.0, 1.0, 1.0 );
844     cl->add( tmp4 );
845
846     // texture coordinates
847     size = tex_index.size();
848     Point3D texcoord;
849     ssgTexCoordArray *tl = new ssgTexCoordArray( size );
850     if ( size == 1 ) {
851         texcoord = texcoords[ tex_index[0] ];
852         sgSetVec2( tmp2, texcoord[0], texcoord[1] );
853         sgSetVec2( tmp2, texcoord[0], texcoord[1] );
854         if ( tex_width > 0 ) {
855             tmp2[0] *= (1000.0 / tex_width);
856         }
857         if ( tex_height > 0 ) {
858             tmp2[1] *= (1000.0 / tex_height);
859         }
860         tl -> add( tmp2 );
861     } else if ( size > 1 ) {
862         for ( i = 0; i < size; ++i ) {
863             texcoord = texcoords[ tex_index[i] ];
864             sgSetVec2( tmp2, texcoord[0], texcoord[1] );
865             if ( tex_width > 0 ) {
866                 tmp2[0] *= (1000.0 / tex_width);
867             }
868             if ( tex_height > 0 ) {
869                 tmp2[1] *= (1000.0 / tex_height);
870             }
871             tl -> add( tmp2 );
872         }
873     }
874
875     ssgLeaf *leaf = new ssgVtxTable ( ty, vl, nl, tl, cl );
876
877     // lookup the state record
878
879     leaf->setState( state );
880
881     if ( calc_lights ) {
882         if ( coverage > 0.0 ) {
883             if ( coverage < 10000.0 ) {
884                 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
885                        << coverage << ", pushing up to 10000");
886                 coverage = 10000;
887             }
888             gen_random_surface_points(leaf, lights, coverage);
889         }
890     }
891
892     return leaf;
893 }
894
895
896 // Load an Binary obj file
897 bool fgBinObjLoad( const string& path, const bool is_base,
898                    Point3D *center,
899                    double *bounding_radius,
900                    ssgBranch* geometry,
901                    ssgBranch* rwy_lights,
902                    ssgVertexArray *ground_lights )
903 {
904     SGBinObject obj;
905
906     if ( ! obj.read_bin( path ) ) {
907         return false;
908     }
909
910     geometry->setName( (char *)path.c_str() );
911    
912     if ( is_base ) {
913         // reference point (center offset/bounding sphere)
914         *center = obj.get_gbs_center();
915         *bounding_radius = obj.get_gbs_radius();
916     }
917
918     point_list nodes = obj.get_wgs84_nodes();
919     point_list colors = obj.get_colors();
920     point_list normals = obj.get_normals();
921     point_list texcoords = obj.get_texcoords();
922
923     string material, tmp_mat;
924     int_list vertex_index;
925     int_list normal_index;
926     int_list tex_index;
927
928     int i;
929     bool is_lighting = false;
930
931     // generate points
932     string_list pt_materials = obj.get_pt_materials();
933     group_list pts_v = obj.get_pts_v();
934     group_list pts_n = obj.get_pts_n();
935     for ( i = 0; i < (int)pts_v.size(); ++i ) {
936         // cout << "pts_v.size() = " << pts_v.size() << endl;
937         tmp_mat = pt_materials[i];
938         if ( tmp_mat.substr(0, 3) == "RWY" ) {
939             material = "LIGHTS";
940             is_lighting = true;
941         } else {
942             material = tmp_mat;
943         }
944         vertex_index = pts_v[i];
945         tex_index.clear();
946         ssgLeaf *leaf = gen_leaf( path, GL_POINTS, material,
947                                   nodes, normals, texcoords,
948                                   vertex_index, normal_index, tex_index,
949                                   false, ground_lights );
950
951         if ( is_lighting ) {
952             rwy_lights->addKid( leaf );
953         } else {
954             geometry->addKid( leaf );
955         }
956     }
957
958     // generate triangles
959     string_list tri_materials = obj.get_tri_materials();
960     group_list tris_v = obj.get_tris_v();
961     group_list tris_n = obj.get_tris_n();
962     group_list tris_tc = obj.get_tris_tc();
963     for ( i = 0; i < (int)tris_v.size(); ++i ) {
964         material = tri_materials[i];
965         vertex_index = tris_v[i];
966         normal_index = tris_n[i];
967         tex_index = tris_tc[i];
968         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLES, material,
969                                   nodes, normals, texcoords,
970                                   vertex_index, normal_index, tex_index,
971                                   is_base, ground_lights );
972
973         geometry->addKid( leaf );
974     }
975
976     // generate strips
977     string_list strip_materials = obj.get_strip_materials();
978     group_list strips_v = obj.get_strips_v();
979     group_list strips_n = obj.get_strips_n();
980     group_list strips_tc = obj.get_strips_tc();
981     for ( i = 0; i < (int)strips_v.size(); ++i ) {
982         material = strip_materials[i];
983         vertex_index = strips_v[i];
984         normal_index = strips_n[i];
985         tex_index = strips_tc[i];
986         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_STRIP, material,
987                                   nodes, normals, texcoords,
988                                   vertex_index, normal_index, tex_index,
989                                   is_base, ground_lights );
990
991         geometry->addKid( leaf );
992     }
993
994     // generate fans
995     string_list fan_materials = obj.get_fan_materials();
996     group_list fans_v = obj.get_fans_v();
997     group_list fans_n = obj.get_fans_n();
998     group_list fans_tc = obj.get_fans_tc();
999     for ( i = 0; i < (int)fans_v.size(); ++i ) {
1000         material = fan_materials[i];
1001         vertex_index = fans_v[i];
1002         normal_index = fans_n[i];
1003         tex_index = fans_tc[i];
1004         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_FAN, material,
1005                                   nodes, normals, texcoords,
1006                                   vertex_index, normal_index, tex_index,
1007                                   is_base, ground_lights );
1008
1009         geometry->addKid( leaf );
1010     }
1011
1012     return true;
1013 }