]> git.mxchange.org Git - flightgear.git/blob - src/Objects/obj.cxx
Started functional decomposition for dynamic objects.
[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 <Time/light.hxx>
56 #include <Scenery/tileentry.hxx>
57
58 #include "newmat.hxx"
59 #include "matlib.hxx"
60 #include "obj.hxx"
61
62 SG_USING_STD(string);
63 SG_USING_STD(vector);
64
65
66 typedef vector < int > int_list;
67 typedef int_list::iterator int_list_iterator;
68 typedef int_list::const_iterator int_point_list_iterator;
69
70
71 static double normals[FG_MAX_NODES][3];
72 static double tex_coords[FG_MAX_NODES*3][3];
73
74 static int
75 runway_lights_predraw (ssgEntity * e)
76 {
77                                 // Turn on lights only at night
78     float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
79     return int(sun_angle > 90.0);
80 }
81
82
83 #define FG_TEX_CONSTANT 69.0
84
85 // Calculate texture coordinates for a given point.
86 static Point3D local_calc_tex_coords(const Point3D& node, const Point3D& ref) {
87     Point3D cp;
88     Point3D pp;
89     // double tmplon, tmplat;
90
91     // cout << "-> " << node[0] << " " << node[1] << " " << node[2] << endl;
92     // cout << "-> " << ref.x() << " " << ref.y() << " " << ref.z() << endl;
93
94     cp = Point3D( node[0] + ref.x(),
95                   node[1] + ref.y(),
96                   node[2] + ref.z() );
97
98     pp = sgCartToPolar3d(cp);
99
100     // tmplon = pp.lon() * SGD_RADIANS_TO_DEGREES;
101     // tmplat = pp.lat() * SGD_RADIANS_TO_DEGREES;
102     // cout << tmplon << " " << tmplat << endl;
103
104     pp.setx( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.x(), 11.0) );
105     pp.sety( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.y(), 11.0) );
106
107     if ( pp.x() < 0.0 ) {
108         pp.setx( pp.x() + 11.0 );
109     }
110
111     if ( pp.y() < 0.0 ) {
112         pp.sety( pp.y() + 11.0 );
113     }
114
115     // cout << pp << endl;
116
117     return(pp);
118 }
119
120
121 // Generate an ocean tile
122 bool fgGenTile( const string& path, SGBucket b,
123                       Point3D *center,
124                       double *bounding_radius,
125                       ssgBranch* geometry )
126 {
127     FGNewMat *newmat;
128
129     ssgSimpleState *state = NULL;
130
131     geometry -> setName ( (char *)path.c_str() ) ;
132
133     double tex_width = 1000.0;
134     // double tex_height;
135
136     // find Ocean material in the properties list
137     newmat = material_lib.find( "Ocean" );
138     if ( newmat != NULL ) {
139         // set the texture width and height values for this
140         // material
141         tex_width = newmat->get_xsize();
142         // tex_height = newmat->get_ysize();
143         
144         // set ssgState
145         state = newmat->get_state();
146     } else {
147         SG_LOG( SG_TERRAIN, SG_ALERT, 
148                 "Ack! unknown usemtl name = " << "Ocean" 
149                 << " in " << path );
150     }
151
152     // Calculate center point
153     double clon = b.get_center_lon();
154     double clat = b.get_center_lat();
155     double height = b.get_height();
156     double width = b.get_width();
157
158     *center = sgGeodToCart( Point3D(clon*SGD_DEGREES_TO_RADIANS,
159                                     clat*SGD_DEGREES_TO_RADIANS,
160                                     0.0) );
161     // cout << "center = " << center << endl;;
162     
163     // Caculate corner vertices
164     Point3D geod[4];
165     geod[0] = Point3D( clon - width/2.0, clat - height/2.0, 0.0 );
166     geod[1] = Point3D( clon + width/2.0, clat - height/2.0, 0.0 );
167     geod[2] = Point3D( clon + width/2.0, clat + height/2.0, 0.0 );
168     geod[3] = Point3D( clon - width/2.0, clat + height/2.0, 0.0 );
169
170     Point3D rad[4];
171     int i;
172     for ( i = 0; i < 4; ++i ) {
173         rad[i] = Point3D( geod[i].x() * SGD_DEGREES_TO_RADIANS,
174                           geod[i].y() * SGD_DEGREES_TO_RADIANS,
175                           geod[i].z() );
176     }
177
178     Point3D cart[4], rel[4];
179     for ( i = 0; i < 4; ++i ) {
180         cart[i] = sgGeodToCart(rad[i]);
181         rel[i] = cart[i] - *center;
182         // cout << "corner " << i << " = " << cart[i] << endl;
183     }
184
185     // Calculate bounding radius
186     *bounding_radius = center->distance3D( cart[0] );
187     // cout << "bounding radius = " << t->bounding_radius << endl;
188
189     // Calculate normals
190     Point3D normals[4];
191     for ( i = 0; i < 4; ++i ) {
192         double length = cart[i].distance3D( Point3D(0.0) );
193         normals[i] = cart[i] / length;
194         // cout << "normal = " << normals[i] << endl;
195     }
196
197     // Calculate texture coordinates
198     point_list geod_nodes;
199     geod_nodes.clear();
200     int_list rectangle;
201     rectangle.clear();
202     for ( i = 0; i < 4; ++i ) {
203         geod_nodes.push_back( geod[i] );
204         rectangle.push_back( i );
205     }
206     point_list texs = calc_tex_coords( b, geod_nodes, rectangle, 
207                                        1000.0 / tex_width );
208
209     // Allocate ssg structure
210     ssgVertexArray   *vl = new ssgVertexArray( 4 );
211     ssgNormalArray   *nl = new ssgNormalArray( 4 );
212     ssgTexCoordArray *tl = new ssgTexCoordArray( 4 );
213     ssgColourArray   *cl = new ssgColourArray( 1 );
214
215     sgVec4 color;
216     sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
217     cl->add( color );
218
219     // sgVec3 *vtlist = new sgVec3 [ 4 ];
220     // t->vec3_ptrs.push_back( vtlist );
221     // sgVec3 *vnlist = new sgVec3 [ 4 ];
222     // t->vec3_ptrs.push_back( vnlist );
223     // sgVec2 *tclist = new sgVec2 [ 4 ];
224     // t->vec2_ptrs.push_back( tclist );
225
226     sgVec2 tmp2;
227     sgVec3 tmp3;
228     for ( i = 0; i < 4; ++i ) {
229         sgSetVec3( tmp3, 
230                    rel[i].x(), rel[i].y(), rel[i].z() );
231         vl->add( tmp3 );
232
233         sgSetVec3( tmp3, 
234                    normals[i].x(), normals[i].y(), normals[i].z() );
235         nl->add( tmp3 );
236
237         sgSetVec2( tmp2, texs[i].x(), texs[i].y());
238         tl->add( tmp2 );
239     }
240     
241     ssgLeaf *leaf = 
242         new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
243
244     leaf->setState( state );
245
246     geometry->addKid( leaf );
247
248     return true;
249 }
250
251
252 static void random_pt_inside_tri( float *res,
253                                   float *n1, float *n2, float *n3 )
254 {
255     sgVec3 p1, p2, p3;
256
257     double a = sg_random();
258     double b = sg_random();
259     if ( a + b > 1.0 ) {
260         a = 1.0 - a;
261         b = 1.0 - b;
262     }
263     double c = 1 - a - b;
264
265     sgScaleVec3( p1, n1, a );
266     sgScaleVec3( p2, n2, b );
267     sgScaleVec3( p3, n3, c );
268
269     sgAddVec3( res, p1, p2 );
270     sgAddVec3( res, p3 );
271 }
272
273
274 static void gen_random_surface_points( ssgLeaf *leaf, ssgVertexArray *lights,
275                                        double factor ) {
276     int num = leaf->getNumTriangles();
277     if ( num > 0 ) {
278         short int n1, n2, n3;
279         float *p1, *p2, *p3;
280         sgVec3 result;
281
282         // generate a repeatable random seed
283         p1 = leaf->getVertex( 0 );
284         unsigned int seed = (unsigned int)p1[0];
285         sg_srandom( seed );
286
287         for ( int i = 0; i < num; ++i ) {
288             leaf->getTriangle( i, &n1, &n2, &n3 );
289             p1 = leaf->getVertex(n1);
290             p2 = leaf->getVertex(n2);
291             p3 = leaf->getVertex(n3);
292             double area = sgTriArea( p1, p2, p3 );
293             double num = area / factor;
294
295             // generate a light point for each unit of area
296             while ( num > 1.0 ) {
297                 random_pt_inside_tri( result, p1, p2, p3 );
298                 lights->add( result );
299                 num -= 1.0;
300             }
301             // for partial units of area, use a zombie door method to
302             // create the proper random chance of a light being created
303             // for this triangle
304             if ( num > 0.0 ) {
305                 if ( sg_random() <= num ) {
306                     // a zombie made it through our door
307                     random_pt_inside_tri( result, p1, p2, p3 );
308                     lights->add( result );
309                 }
310             }
311         }
312     }
313 }
314
315
316 /**
317  * Add an object to a random location inside a triangle.
318  *
319  * @param p1 The first vertex of the triangle.
320  * @param p2 The second vertex of the triangle.
321  * @param p3 The third vertex of the triangle.
322  * @param center The center of the triangle.
323  * @param ROT The world-up rotation matrix.
324  * @param mat The material object.
325  * @param object_index The index of the dynamically-placed object in
326  *        the material.
327  * @param branch The branch where the object should be added to the
328  *        scene graph.
329  */
330 static void
331 add_object_to_triangle (sgVec3 p1, sgVec3 p2, sgVec3 p3, sgVec3 center,
332                         sgMat4 ROT, FGNewMat * mat, int object_index,
333                         ssgBranch * branch)
334 {
335     sgVec3 result;
336
337     random_pt_inside_tri(result, p1, p2, p3);
338     sgSubVec3(result, center);
339     sgMat4 OBJ_pos, OBJ;
340     sgMakeTransMat4(OBJ_pos, result);
341     sgCopyMat4(OBJ, ROT);
342     sgPostMultMat4(OBJ, OBJ_pos);
343     ssgTransform * pos = new ssgTransform;
344     pos->setTransform(OBJ);
345     float obj_range = mat->get_object_lod(object_index);
346     float range_div = (sg_random() * obj_range);
347     if (range_div < 0.0000001) {
348       // avoid a divide by zero error
349       range_div = 1.0;
350     }
351     float random_range = 160.0 * obj_range / range_div + obj_range;
352     float ranges[] = {0, random_range};
353     ssgRangeSelector *range = new ssgRangeSelector;
354     range->setRanges(ranges, 2);
355     range->addKid(mat->get_object(object_index));
356     pos->addKid(range);
357     branch->addKid(pos);
358 }
359
360
361 /**
362  * Create a rotation matrix to align an object for the current lat/lon.
363  *
364  * By default, objects are aligned for the north pole.  This code
365  * calculates a matrix to rotate them for the surface of the earth in
366  * the current location.
367  *
368  * TODO: there should be a single version of this method somewhere
369  * for all of SimGear.
370  *
371  * @param ROT The resulting rotation matrix.
372  * @param hdg_deg The object heading in degrees.
373  * @param lon_deg The longitude in degrees.
374  * @param lat_deg The latitude in degrees.
375  */
376 static void
377 makeWorldUpRotationMatrix (sgMat4 ROT, double hdg_deg,
378                            double lon_deg, double lat_deg)
379 {
380     sgVec3 obj_right, obj_up;
381     sgSetVec3(obj_right, 0.0, 1.0, 0.0); // Y axis
382     sgSetVec3(obj_up, 0.0, 0.0, 1.0); // Z axis
383     sgMat4 ROT_lon, ROT_lat, ROT_hdg;
384     sgMakeRotMat4(ROT_lon, lon_deg, obj_up);
385     sgMakeRotMat4(ROT_lat, 90 - lat_deg, obj_right);
386     sgMakeRotMat4(ROT_hdg, hdg_deg, obj_up);
387     sgCopyMat4(ROT, ROT_hdg);
388     sgPostMultMat4(ROT, ROT_lat);
389     sgPostMultMat4(ROT, ROT_lon);
390 }
391
392
393 static void
394 gen_random_surface_objects (ssgLeaf *leaf,
395                             ssgBranch *branch,
396                             float lon_deg,
397                             float lat_deg,
398                             const string &material_name)
399 {
400     FGNewMat * mat = material_lib.find(material_name);
401     if (mat == 0) {
402       SG_LOG(SG_INPUT, SG_ALERT, "Unknown material " << material_name);
403       return;
404     }
405
406     int num = leaf->getNumTriangles();
407     float hdg_deg = 0.0;        // do something here later
408
409
410     sgMat4 ROT;
411     makeWorldUpRotationMatrix(ROT, hdg_deg, lon_deg, lat_deg);
412
413     if ( num > 0 ) {
414         short int n1, n2, n3;
415         float *p1, *p2, *p3;
416         sgVec3 result;
417
418         // generate a repeatable random seed
419         p1 = leaf->getVertex( 0 );
420         unsigned int seed = (unsigned int)p1[0];
421         sg_srandom( seed );
422
423         int num_objects = mat->get_object_count();
424         for ( int i = 0; i < num; ++i ) {
425             leaf->getTriangle( i, &n1, &n2, &n3 );
426             p1 = leaf->getVertex(n1);
427             p2 = leaf->getVertex(n2);
428             p3 = leaf->getVertex(n3);
429             double area = sgTriArea( p1, p2, p3 );
430                                 // Set up a single center point for LOD
431             sgVec3 center;
432             sgSetVec3(center,
433                       (p1[0] + p2[0] + p3[0]) / 3.0,
434                       (p1[1] + p2[1] + p3[1]) / 3.0,
435                       (p1[2] + p2[2] + p3[2]) / 3.0);
436             ssgTransform * location = new ssgTransform;
437             sgMat4 TRANS;
438             sgMakeTransMat4(TRANS, center);
439             location->setTransform(TRANS);
440
441             for (int j = 0; j < num_objects; j++) {
442               double num = area / mat->get_object_coverage(j);
443               float ranges[] = {0, mat->get_object_group_lod(j)};
444               ssgRangeSelector * lod = new ssgRangeSelector;
445               lod->setRanges(ranges, 2);
446               lod->addKid(location);
447               branch->addKid(lod);
448               
449               // place an object each unit of area
450               while ( num > 1.0 ) {
451                 add_object_to_triangle(p1, p2, p3, center,
452                                        ROT, mat, j, location);
453                 num -= 1.0;
454               }
455               // for partial units of area, use a zombie door method to
456               // create the proper random chance of an object being created
457               // for this triangle
458               if ( num > 0.0 ) {
459                 if ( sg_random() <= num ) {
460                   // a zombie made it through our door
461                   add_object_to_triangle(p1, p2, p3, center,
462                                          ROT, mat, j, location);
463                 }
464               }
465             }
466         }
467     }
468 }
469
470
471 \f
472 ////////////////////////////////////////////////////////////////////////
473 // Scenery loaders.
474 ////////////////////////////////////////////////////////////////////////
475
476
477 // Load an Ascii obj file
478 ssgBranch *fgAsciiObjLoad( const string& path, FGTileEntry *t,
479                            ssgVertexArray *lights, const bool is_base)
480 {
481     FGNewMat *newmat = NULL;
482     string material;
483     float coverage = -1;
484     Point3D pp;
485     // sgVec3 approx_normal;
486     // double normal[3], scale = 0.0;
487     // double x, y, z, xmax, xmin, ymax, ymin, zmax, zmin;
488     // GLfloat sgenparams[] = { 1.0, 0.0, 0.0, 0.0 };
489     // GLint display_list = 0;
490     int shading;
491     bool in_faces = false;
492     int vncount, vtcount;
493     int n1 = 0, n2 = 0, n3 = 0;
494     int tex;
495     // int last1 = 0, last2 = 0;
496     bool odd = false;
497     point_list nodes;
498     Point3D node;
499     Point3D center;
500     double scenery_version = 0.0;
501     double tex_width = 1000.0, tex_height = 1000.0;
502     bool shared_done = false;
503     int_list fan_vertices;
504     int_list fan_tex_coords;
505     int i;
506     ssgSimpleState *state = NULL;
507     sgVec3 *vtlist, *vnlist;
508     sgVec2 *tclist;
509
510     ssgBranch *tile = new ssgBranch () ;
511
512     tile -> setName ( (char *)path.c_str() ) ;
513
514     // Attempt to open "path.gz" or "path"
515     sg_gzifstream in( path );
516     if ( ! in.is_open() ) {
517         SG_LOG( SG_TERRAIN, SG_DEBUG, "Cannot open file: " << path );
518         SG_LOG( SG_TERRAIN, SG_DEBUG, "default to ocean tile: " << path );
519
520         delete tile;
521
522         return NULL;
523     }
524
525     shading = fgGetBool("/sim/rendering/shading");
526
527     if ( is_base ) {
528         t->ncount = 0;
529     }
530     vncount = 0;
531     vtcount = 0;
532     if ( is_base ) {
533         t->bounding_radius = 0.0;
534     }
535     center = t->center;
536
537     // StopWatch stopwatch;
538     // stopwatch.start();
539
540     // ignore initial comments and blank lines. (priming the pump)
541     // in >> skipcomment;
542     // string line;
543
544     string token;
545     char c;
546
547 #ifdef __MWERKS__
548     while ( in.get(c) && c  != '\0' ) {
549         in.putback(c);
550 #else
551     while ( ! in.eof() ) {
552 #endif
553
554         in >> ::skipws;
555
556         if ( in.get( c ) && c == '#' ) {
557             // process a comment line
558
559             // getline( in, line );
560             // cout << "comment = " << line << endl;
561
562             in >> token;
563
564             if ( token == "Version" ) {
565                 // read scenery versions number
566                 in >> scenery_version;
567                 // cout << "scenery_version = " << scenery_version << endl;
568                 if ( scenery_version > 0.4 ) {
569                     SG_LOG( SG_TERRAIN, SG_ALERT, 
570                             "\nYou are attempting to load a tile format that\n"
571                             << "is newer than this version of flightgear can\n"
572                             << "handle.  You should upgrade your copy of\n"
573                             << "FlightGear to the newest version.  For\n"
574                             << "details, please see:\n"
575                             << "\n    http://www.flightgear.org\n" );
576                     exit(-1);
577                 }
578             } else if ( token == "gbs" ) {
579                 // reference point (center offset)
580                 if ( is_base ) {
581                     in >> t->center >> t->bounding_radius;
582                 } else {
583                     Point3D junk1;
584                     double junk2;
585                     in >> junk1 >> junk2;
586                 }
587                 center = t->center;
588                 // cout << "center = " << center 
589                 //      << " radius = " << t->bounding_radius << endl;
590             } else if ( token == "bs" ) {
591                 // reference point (center offset)
592                 // (skip past this)
593                 Point3D junk1;
594                 double junk2;
595                 in >> junk1 >> junk2;
596             } else if ( token == "usemtl" ) {
597                 // material property specification
598
599                 // if first usemtl with shared_done = false, then set
600                 // shared_done true and build the ssg shared lists
601                 if ( ! shared_done ) {
602                     // sanity check
603                     if ( (int)nodes.size() != vncount ) {
604                         SG_LOG( SG_TERRAIN, SG_ALERT, 
605                                 "Tile has mismatched nodes = " << nodes.size()
606                                 << " and normals = " << vncount << " : " 
607                                 << path );
608                         // exit(-1);
609                     }
610                     shared_done = true;
611
612                     vtlist = new sgVec3 [ nodes.size() ];
613                     t->vec3_ptrs.push_back( vtlist );
614                     vnlist = new sgVec3 [ vncount ];
615                     t->vec3_ptrs.push_back( vnlist );
616                     tclist = new sgVec2 [ vtcount ];
617                     t->vec2_ptrs.push_back( tclist );
618
619                     for ( i = 0; i < (int)nodes.size(); ++i ) {
620                         sgSetVec3( vtlist[i], 
621                                    nodes[i][0], nodes[i][1], nodes[i][2] );
622                     }
623                     for ( i = 0; i < vncount; ++i ) {
624                         sgSetVec3( vnlist[i], 
625                                    normals[i][0], 
626                                    normals[i][1],
627                                    normals[i][2] );
628                     }
629                     for ( i = 0; i < vtcount; ++i ) {
630                         sgSetVec2( tclist[i],
631                                    tex_coords[i][0],
632                                    tex_coords[i][1] );
633                     }
634                 }
635
636                 // display_list = xglGenLists(1);
637                 // xglNewList(display_list, GL_COMPILE);
638                 // printf("xglGenLists(); xglNewList();\n");
639                 in_faces = false;
640
641                 // scan the material line
642                 in >> material;
643                 
644                 // find this material in the properties list
645
646                 newmat = material_lib.find( material );
647                 if ( newmat == NULL ) {
648                     // see if this is an on the fly texture
649                     string file = path;
650                     int pos = file.rfind( "/" );
651                     file = file.substr( 0, pos );
652                     // cout << "current file = " << file << endl;
653                     file += "/";
654                     file += material;
655                     // cout << "current file = " << file << endl;
656                     if ( ! material_lib.add_item( file ) ) {
657                         SG_LOG( SG_TERRAIN, SG_ALERT, 
658                                 "Ack! unknown usemtl name = " << material 
659                                 << " in " << path );
660                     } else {
661                         // locate our newly created material
662                         newmat = material_lib.find( material );
663                         if ( newmat == NULL ) {
664                             SG_LOG( SG_TERRAIN, SG_ALERT, 
665                                     "Ack! bad on the fly materia create = "
666                                     << material << " in " << path );
667                         }
668                     }
669                 }
670
671                 if ( newmat != NULL ) {
672                     // set the texture width and height values for this
673                     // material
674                     tex_width = newmat->get_xsize();
675                     tex_height = newmat->get_ysize();
676                     state = newmat->get_state();
677                     coverage = newmat->get_light_coverage();
678                     // cout << "(w) = " << tex_width << " (h) = "
679                     //      << tex_width << endl;
680                 } else {
681                     coverage = -1;
682                 }
683             } else {
684                 // unknown comment, just gobble the input until the
685                 // end of line
686
687                 in >> skipeol;
688             }
689         } else {
690             in.putback( c );
691         
692             in >> token;
693
694             // cout << "token = " << token << endl;
695
696             if ( token == "vn" ) {
697                 // vertex normal
698                 if ( vncount < FG_MAX_NODES ) {
699                     in >> normals[vncount][0]
700                        >> normals[vncount][1]
701                        >> normals[vncount][2];
702                     vncount++;
703                 } else {
704                     SG_LOG( SG_TERRAIN, SG_ALERT, 
705                             "Read too many vertex normals in " << path 
706                             << " ... dying :-(" );
707                     exit(-1);
708                 }
709             } else if ( token == "vt" ) {
710                 // vertex texture coordinate
711                 if ( vtcount < FG_MAX_NODES*3 ) {
712                     in >> tex_coords[vtcount][0]
713                        >> tex_coords[vtcount][1];
714                     vtcount++;
715                 } else {
716                     SG_LOG( SG_TERRAIN, SG_ALERT, 
717                             "Read too many vertex texture coords in " << path
718                             << " ... dying :-("
719                             );
720                     exit(-1);
721                 }
722             } else if ( token == "v" ) {
723                 // node (vertex)
724                 if ( t->ncount < FG_MAX_NODES ) {
725                     /* in >> nodes[t->ncount][0]
726                        >> nodes[t->ncount][1]
727                        >> nodes[t->ncount][2]; */
728                     in >> node;
729                     nodes.push_back(node);
730                     if ( is_base ) {
731                         t->ncount++;
732                     }
733                 } else {
734                     SG_LOG( SG_TERRAIN, SG_ALERT, 
735                             "Read too many nodes in " << path 
736                             << " ... dying :-(");
737                     exit(-1);
738                 }
739             } else if ( (token == "tf") || (token == "ts") || (token == "f") ) {
740                 // triangle fan, strip, or individual face
741                 // SG_LOG( SG_TERRAIN, SG_INFO, "new fan or strip");
742
743                 fan_vertices.clear();
744                 fan_tex_coords.clear();
745                 odd = true;
746
747                 // xglBegin(GL_TRIANGLE_FAN);
748
749                 in >> n1;
750                 fan_vertices.push_back( n1 );
751                 // xglNormal3dv(normals[n1]);
752                 if ( in.get( c ) && c == '/' ) {
753                     in >> tex;
754                     fan_tex_coords.push_back( tex );
755                     if ( scenery_version >= 0.4 ) {
756                         if ( tex_width > 0 ) {
757                             tclist[tex][0] *= (1000.0 / tex_width);
758                         }
759                         if ( tex_height > 0 ) {
760                             tclist[tex][1] *= (1000.0 / tex_height);
761                         }
762                     }
763                     pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
764                     pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
765                 } else {
766                     in.putback( c );
767                     pp = local_calc_tex_coords(nodes[n1], center);
768                 }
769                 // xglTexCoord2f(pp.x(), pp.y());
770                 // xglVertex3dv(nodes[n1].get_n());
771
772                 in >> n2;
773                 fan_vertices.push_back( n2 );
774                 // xglNormal3dv(normals[n2]);
775                 if ( in.get( c ) && c == '/' ) {
776                     in >> tex;
777                     fan_tex_coords.push_back( tex );
778                     if ( scenery_version >= 0.4 ) {
779                         if ( tex_width > 0 ) {
780                             tclist[tex][0] *= (1000.0 / tex_width);
781                         }
782                         if ( tex_height > 0 ) {
783                             tclist[tex][1] *= (1000.0 / tex_height);
784                         }
785                     }
786                     pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
787                     pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
788                 } else {
789                     in.putback( c );
790                     pp = local_calc_tex_coords(nodes[n2], center);
791                 }
792                 // xglTexCoord2f(pp.x(), pp.y());
793                 // xglVertex3dv(nodes[n2].get_n());
794                 
795                 // read all subsequent numbers until next thing isn't a number
796                 while ( true ) {
797                     in >> ::skipws;
798
799                     char c;
800                     in.get(c);
801                     in.putback(c);
802                     if ( ! isdigit(c) || in.eof() ) {
803                         break;
804                     }
805
806                     in >> n3;
807                     fan_vertices.push_back( n3 );
808                     // cout << "  triangle = "
809                     //      << n1 << "," << n2 << "," << n3
810                     //      << endl;
811                     // xglNormal3dv(normals[n3]);
812                     if ( in.get( c ) && c == '/' ) {
813                         in >> tex;
814                         fan_tex_coords.push_back( tex );
815                         if ( scenery_version >= 0.4 ) {
816                             if ( tex_width > 0 ) {
817                                 tclist[tex][0] *= (1000.0 / tex_width);
818                             }
819                             if ( tex_height > 0 ) {
820                                 tclist[tex][1] *= (1000.0 / tex_height);
821                             }
822                         }
823                         pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
824                         pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
825                     } else {
826                         in.putback( c );
827                         pp = local_calc_tex_coords(nodes[n3], center);
828                     }
829                     // xglTexCoord2f(pp.x(), pp.y());
830                     // xglVertex3dv(nodes[n3].get_n());
831
832                     if ( (token == "tf") || (token == "f") ) {
833                         // triangle fan
834                         n2 = n3;
835                     } else {
836                         // triangle strip
837                         odd = !odd;
838                         n1 = n2;
839                         n2 = n3;
840                     }
841                 }
842
843                 // xglEnd();
844
845                 // build the ssg entity
846                 int size = (int)fan_vertices.size();
847                 ssgVertexArray   *vl = new ssgVertexArray( size );
848                 ssgNormalArray   *nl = new ssgNormalArray( size );
849                 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
850                 ssgColourArray   *cl = new ssgColourArray( 1 );
851
852                 sgVec4 color;
853                 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
854                 cl->add( color );
855
856                 sgVec2 tmp2;
857                 sgVec3 tmp3;
858                 for ( i = 0; i < size; ++i ) {
859                     sgCopyVec3( tmp3, vtlist[ fan_vertices[i] ] );
860                     vl -> add( tmp3 );
861
862                     sgCopyVec3( tmp3, vnlist[ fan_vertices[i] ] );
863                     nl -> add( tmp3 );
864
865                     sgCopyVec2( tmp2, tclist[ fan_tex_coords[i] ] );
866                     tl -> add( tmp2 );
867                 }
868
869                 ssgLeaf *leaf = NULL;
870                 if ( token == "tf" ) {
871                     // triangle fan
872                     leaf = 
873                         new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
874                 } else if ( token == "ts" ) {
875                     // triangle strip
876                     leaf = 
877                         new ssgVtxTable ( GL_TRIANGLE_STRIP, vl, nl, tl, cl );
878                 } else if ( token == "f" ) {
879                     // triangle
880                     leaf = 
881                         new ssgVtxTable ( GL_TRIANGLES, vl, nl, tl, cl );
882                 }
883                 // leaf->makeDList();
884                 leaf->setState( state );
885
886                 tile->addKid( leaf );
887
888                 if ( is_base ) {
889                     if ( coverage > 0.0 ) {
890                         if ( coverage < 10000.0 ) {
891                             SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
892                                    << coverage << ", pushing up to 10000");
893                             coverage = 10000;
894                         }
895                         gen_random_surface_points(leaf, lights, coverage);
896                     }
897                 }
898             } else {
899                 SG_LOG( SG_TERRAIN, SG_WARN, "Unknown token in " 
900                         << path << " = " << token );
901             }
902
903             // eat white space before start of while loop so if we are
904             // done with useful input it is noticed before hand.
905             in >> ::skipws;
906         }
907     }
908
909     if ( is_base ) {
910         t->nodes = nodes;
911     }
912
913     // stopwatch.stop();
914     // SG_LOG( SG_TERRAIN, SG_DEBUG, 
915     //     "Loaded " << path << " in " 
916     //     << stopwatch.elapsedSeconds() << " seconds" );
917
918     return tile;
919 }
920
921
922 ssgLeaf *gen_leaf( const string& path,
923                    const GLenum ty, const string& material,
924                    const point_list& nodes, const point_list& normals,
925                    const point_list& texcoords,
926                    const int_list node_index,
927                    const int_list normal_index,
928                    const int_list& tex_index,
929                    const bool calc_lights, ssgVertexArray *lights )
930 {
931     double tex_width = 1000.0, tex_height = 1000.0;
932     ssgSimpleState *state = NULL;
933     float coverage = -1;
934
935     FGNewMat *newmat = material_lib.find( material );
936     if ( newmat == NULL ) {
937         // see if this is an on the fly texture
938         string file = path;
939         int pos = file.rfind( "/" );
940         file = file.substr( 0, pos );
941         // cout << "current file = " << file << endl;
942         file += "/";
943         file += material;
944         // cout << "current file = " << file << endl;
945         if ( ! material_lib.add_item( file ) ) {
946             SG_LOG( SG_TERRAIN, SG_ALERT, 
947                     "Ack! unknown usemtl name = " << material 
948                     << " in " << path );
949         } else {
950             // locate our newly created material
951             newmat = material_lib.find( material );
952             if ( newmat == NULL ) {
953                 SG_LOG( SG_TERRAIN, SG_ALERT, 
954                         "Ack! bad on the fly material create = "
955                         << material << " in " << path );
956             }
957         }
958     }
959
960     if ( newmat != NULL ) {
961         // set the texture width and height values for this
962         // material
963         tex_width = newmat->get_xsize();
964         tex_height = newmat->get_ysize();
965         state = newmat->get_state();
966         coverage = newmat->get_light_coverage();
967         // cout << "(w) = " << tex_width << " (h) = "
968         //      << tex_width << endl;
969     } else {
970         coverage = -1;
971     }
972
973     sgVec2 tmp2;
974     sgVec3 tmp3;
975     sgVec4 tmp4;
976     int i;
977
978     // vertices
979     int size = node_index.size();
980     if ( size < 1 ) {
981         SG_LOG( SG_TERRAIN, SG_ALERT, "Woh! node list size < 1" );
982         exit(-1);
983     }
984     ssgVertexArray *vl = new ssgVertexArray( size );
985     Point3D node;
986     for ( i = 0; i < size; ++i ) {
987         node = nodes[ node_index[i] ];
988         sgSetVec3( tmp3, node[0], node[1], node[2] );
989         vl -> add( tmp3 );
990     }
991
992     // normals
993     Point3D normal;
994     ssgNormalArray *nl = new ssgNormalArray( size );
995     if ( normal_index.size() ) {
996         // object file specifies normal indices (i.e. normal indices
997         // aren't 'implied'
998         for ( i = 0; i < size; ++i ) {
999             normal = normals[ normal_index[i] ];
1000             sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1001             nl -> add( tmp3 );
1002         }
1003     } else {
1004         // use implied normal indices.  normal index = vertex index.
1005         for ( i = 0; i < size; ++i ) {
1006             normal = normals[ node_index[i] ];
1007             sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1008             nl -> add( tmp3 );
1009         }
1010     }
1011
1012     // colors
1013     ssgColourArray *cl = new ssgColourArray( 1 );
1014     sgSetVec4( tmp4, 1.0, 1.0, 1.0, 1.0 );
1015     cl->add( tmp4 );
1016
1017     // texture coordinates
1018     size = tex_index.size();
1019     Point3D texcoord;
1020     ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1021     if ( size == 1 ) {
1022         texcoord = texcoords[ tex_index[0] ];
1023         sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1024         sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1025         if ( tex_width > 0 ) {
1026             tmp2[0] *= (1000.0 / tex_width);
1027         }
1028         if ( tex_height > 0 ) {
1029             tmp2[1] *= (1000.0 / tex_height);
1030         }
1031         tl -> add( tmp2 );
1032     } else if ( size > 1 ) {
1033         for ( i = 0; i < size; ++i ) {
1034             texcoord = texcoords[ tex_index[i] ];
1035             sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1036             if ( tex_width > 0 ) {
1037                 tmp2[0] *= (1000.0 / tex_width);
1038             }
1039             if ( tex_height > 0 ) {
1040                 tmp2[1] *= (1000.0 / tex_height);
1041             }
1042             tl -> add( tmp2 );
1043         }
1044     }
1045
1046     ssgLeaf *leaf = new ssgVtxTable ( ty, vl, nl, tl, cl );
1047
1048     // lookup the state record
1049
1050     leaf->setState( state );
1051
1052     if ( calc_lights ) {
1053         if ( coverage > 0.0 ) {
1054             if ( coverage < 10000.0 ) {
1055                 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1056                        << coverage << ", pushing up to 10000");
1057                 coverage = 10000;
1058             }
1059             gen_random_surface_points(leaf, lights, coverage);
1060         }
1061     }
1062
1063     return leaf;
1064 }
1065
1066
1067 // Load an Binary obj file
1068 bool fgBinObjLoad( const string& path, const bool is_base,
1069                    Point3D *center,
1070                    double *bounding_radius,
1071                    ssgBranch* geometry,
1072                    ssgBranch* rwy_lights,
1073                    ssgVertexArray *ground_lights )
1074 {
1075     SGBinObject obj;
1076     bool use_dynamic_objects =
1077       fgGetBool("/sim/rendering/dynamic-objects", false);
1078
1079     if ( ! obj.read_bin( path ) ) {
1080         return false;
1081     }
1082
1083     geometry->setName( (char *)path.c_str() );
1084    
1085     double geod_lon = 0.0, geod_lat = 0.0, geod_alt = 0.0,
1086       geod_sl_radius = 0.0;
1087     if ( is_base ) {
1088         // reference point (center offset/bounding sphere)
1089         *center = obj.get_gbs_center();
1090         *bounding_radius = obj.get_gbs_radius();
1091
1092                                 // Calculate the geodetic centre of
1093                                 // the tile, for aligning automatic
1094                                 // objects.
1095         Point3D geoc = sgCartToPolar3d(*center);
1096         geod_lon = geoc.lon();
1097         sgGeocToGeod(geoc.lat(), geoc.radius(),
1098                      &geod_lat, &geod_alt, &geod_sl_radius);
1099         geod_lon *= SGD_RADIANS_TO_DEGREES;
1100         geod_lat *= SGD_RADIANS_TO_DEGREES;
1101     }
1102
1103     point_list nodes = obj.get_wgs84_nodes();
1104     point_list colors = obj.get_colors();
1105     point_list normals = obj.get_normals();
1106     point_list texcoords = obj.get_texcoords();
1107
1108     string material, tmp_mat;
1109     int_list vertex_index;
1110     int_list normal_index;
1111     int_list tex_index;
1112
1113     int i;
1114     bool is_lighting = false;
1115
1116     // generate points
1117     string_list pt_materials = obj.get_pt_materials();
1118     group_list pts_v = obj.get_pts_v();
1119     group_list pts_n = obj.get_pts_n();
1120     for ( i = 0; i < (int)pts_v.size(); ++i ) {
1121         // cout << "pts_v.size() = " << pts_v.size() << endl;
1122         tmp_mat = pt_materials[i];
1123         if ( tmp_mat.substr(0, 3) == "RWY" ) {
1124             material = "LIGHTS";
1125             is_lighting = true;
1126         } else {
1127             material = tmp_mat;
1128         }
1129         vertex_index = pts_v[i];
1130         normal_index = pts_n[i];
1131         tex_index.clear();
1132         ssgLeaf *leaf = gen_leaf( path, GL_POINTS, material,
1133                                   nodes, normals, texcoords,
1134                                   vertex_index, normal_index, tex_index,
1135                                   false, ground_lights );
1136
1137         if ( is_lighting ) {
1138             float ranges[] = { 0, 12000 };
1139             leaf->setCallback(SSG_CALLBACK_PREDRAW, runway_lights_predraw);
1140             ssgRangeSelector * lod = new ssgRangeSelector;
1141             lod->setRanges(ranges, 2);
1142             lod->addKid(leaf);
1143             rwy_lights->addKid(lod);
1144         } else {
1145             geometry->addKid( leaf );
1146         }
1147     }
1148
1149     // generate triangles
1150     string_list tri_materials = obj.get_tri_materials();
1151     group_list tris_v = obj.get_tris_v();
1152     group_list tris_n = obj.get_tris_n();
1153     group_list tris_tc = obj.get_tris_tc();
1154     for ( i = 0; i < (int)tris_v.size(); ++i ) {
1155         material = tri_materials[i];
1156         vertex_index = tris_v[i];
1157         normal_index = tris_n[i];
1158         tex_index = tris_tc[i];
1159         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLES, material,
1160                                   nodes, normals, texcoords,
1161                                   vertex_index, normal_index, tex_index,
1162                                   is_base, ground_lights );
1163
1164         if (use_dynamic_objects)
1165           gen_random_surface_objects(leaf, geometry, geod_lon, geod_lat,
1166                                      material);
1167         geometry->addKid( leaf );
1168     }
1169
1170     // generate strips
1171     string_list strip_materials = obj.get_strip_materials();
1172     group_list strips_v = obj.get_strips_v();
1173     group_list strips_n = obj.get_strips_n();
1174     group_list strips_tc = obj.get_strips_tc();
1175     for ( i = 0; i < (int)strips_v.size(); ++i ) {
1176         material = strip_materials[i];
1177         vertex_index = strips_v[i];
1178         normal_index = strips_n[i];
1179         tex_index = strips_tc[i];
1180         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_STRIP, material,
1181                                   nodes, normals, texcoords,
1182                                   vertex_index, normal_index, tex_index,
1183                                   is_base, ground_lights );
1184
1185         if (use_dynamic_objects)
1186           gen_random_surface_objects(leaf, geometry, geod_lon, geod_lat,
1187                                      material);
1188         geometry->addKid( leaf );
1189     }
1190
1191     // generate fans
1192     string_list fan_materials = obj.get_fan_materials();
1193     group_list fans_v = obj.get_fans_v();
1194     group_list fans_n = obj.get_fans_n();
1195     group_list fans_tc = obj.get_fans_tc();
1196     for ( i = 0; i < (int)fans_v.size(); ++i ) {
1197         material = fan_materials[i];
1198         vertex_index = fans_v[i];
1199         normal_index = fans_n[i];
1200         tex_index = fans_tc[i];
1201         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_FAN, material,
1202                                   nodes, normals, texcoords,
1203                                   vertex_index, normal_index, tex_index,
1204                                   is_base, ground_lights );
1205         if (use_dynamic_objects)
1206           gen_random_surface_objects(leaf, geometry, geod_lon, geod_lat,
1207                                      material);
1208         geometry->addKid( leaf );
1209     }
1210
1211     return true;
1212 }