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