]> git.mxchange.org Git - flightgear.git/blob - src/Objects/obj.cxx
Added static port system and a new altimeter model connected to it.
[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/sg_inlines.h>
37 #include <simgear/io/sg_binobj.hxx>
38
39 #include STL_STRING
40 #include <map>                  // STL
41 #include <vector>               // STL
42 #include <ctype.h>              // isdigit()
43
44 #include <simgear/constants.h>
45 #include <simgear/debug/logstream.hxx>
46 #include <simgear/math/point3d.hxx>
47 #include <simgear/math/polar3d.hxx>
48 #include <simgear/math/sg_geodesy.hxx>
49 #include <simgear/math/sg_random.h>
50 #include <simgear/math/vector.hxx>
51 #include <simgear/misc/sgstream.hxx>
52 #include <simgear/misc/stopwatch.hxx>
53 #include <simgear/misc/texcoord.hxx>
54
55 #include <Main/globals.hxx>
56 #include <Main/fg_props.hxx>
57 #include <Time/light.hxx>
58 #include <Scenery/tileentry.hxx>
59
60 #include "newmat.hxx"
61 #include "matlib.hxx"
62 #include "obj.hxx"
63
64 SG_USING_STD(string);
65 SG_USING_STD(vector);
66
67
68 typedef vector < int > int_list;
69 typedef int_list::iterator int_list_iterator;
70 typedef int_list::const_iterator int_point_list_iterator;
71
72
73 static double normals[FG_MAX_NODES][3];
74 static double tex_coords[FG_MAX_NODES*3][3];
75
76 static int
77 runway_lights_predraw (ssgEntity * e)
78 {
79                                 // Turn on lights only at night
80     float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
81     return int(sun_angle > 90.0);
82 }
83
84
85 #define FG_TEX_CONSTANT 69.0
86
87 // Calculate texture coordinates for a given point.
88 static Point3D local_calc_tex_coords(const Point3D& node, const Point3D& ref) {
89     Point3D cp;
90     Point3D pp;
91     // double tmplon, tmplat;
92
93     // cout << "-> " << node[0] << " " << node[1] << " " << node[2] << endl;
94     // cout << "-> " << ref.x() << " " << ref.y() << " " << ref.z() << endl;
95
96     cp = Point3D( node[0] + ref.x(),
97                   node[1] + ref.y(),
98                   node[2] + ref.z() );
99
100     pp = sgCartToPolar3d(cp);
101
102     // tmplon = pp.lon() * SGD_RADIANS_TO_DEGREES;
103     // tmplat = pp.lat() * SGD_RADIANS_TO_DEGREES;
104     // cout << tmplon << " " << tmplat << endl;
105
106     pp.setx( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.x(), 11.0) );
107     pp.sety( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.y(), 11.0) );
108
109     if ( pp.x() < 0.0 ) {
110         pp.setx( pp.x() + 11.0 );
111     }
112
113     if ( pp.y() < 0.0 ) {
114         pp.sety( pp.y() + 11.0 );
115     }
116
117     // cout << pp << endl;
118
119     return(pp);
120 }
121
122
123 // Generate an ocean tile
124 bool fgGenTile( const string& path, SGBucket b,
125                       Point3D *center,
126                       double *bounding_radius,
127                       ssgBranch* geometry )
128 {
129     FGNewMat *newmat;
130
131     ssgSimpleState *state = NULL;
132
133     geometry -> setName ( (char *)path.c_str() ) ;
134
135     double tex_width = 1000.0;
136     // double tex_height;
137
138     // find Ocean material in the properties list
139     newmat = material_lib.find( "Ocean" );
140     if ( newmat != NULL ) {
141         // set the texture width and height values for this
142         // material
143         tex_width = newmat->get_xsize();
144         // tex_height = newmat->get_ysize();
145         
146         // set ssgState
147         state = newmat->get_state();
148     } else {
149         SG_LOG( SG_TERRAIN, SG_ALERT, 
150                 "Ack! unknown usemtl name = " << "Ocean" 
151                 << " in " << path );
152     }
153
154     // Calculate center point
155     double clon = b.get_center_lon();
156     double clat = b.get_center_lat();
157     double height = b.get_height();
158     double width = b.get_width();
159
160     *center = sgGeodToCart( Point3D(clon*SGD_DEGREES_TO_RADIANS,
161                                     clat*SGD_DEGREES_TO_RADIANS,
162                                     0.0) );
163     // cout << "center = " << center << endl;;
164     
165     // Caculate corner vertices
166     Point3D geod[4];
167     geod[0] = Point3D( clon - width/2.0, clat - height/2.0, 0.0 );
168     geod[1] = Point3D( clon + width/2.0, clat - height/2.0, 0.0 );
169     geod[2] = Point3D( clon + width/2.0, clat + height/2.0, 0.0 );
170     geod[3] = Point3D( clon - width/2.0, clat + height/2.0, 0.0 );
171
172     Point3D rad[4];
173     int i;
174     for ( i = 0; i < 4; ++i ) {
175         rad[i] = Point3D( geod[i].x() * SGD_DEGREES_TO_RADIANS,
176                           geod[i].y() * SGD_DEGREES_TO_RADIANS,
177                           geod[i].z() );
178     }
179
180     Point3D cart[4], rel[4];
181     for ( i = 0; i < 4; ++i ) {
182         cart[i] = sgGeodToCart(rad[i]);
183         rel[i] = cart[i] - *center;
184         // cout << "corner " << i << " = " << cart[i] << endl;
185     }
186
187     // Calculate bounding radius
188     *bounding_radius = center->distance3D( cart[0] );
189     // cout << "bounding radius = " << t->bounding_radius << endl;
190
191     // Calculate normals
192     Point3D normals[4];
193     for ( i = 0; i < 4; ++i ) {
194         double length = cart[i].distance3D( Point3D(0.0) );
195         normals[i] = cart[i] / length;
196         // cout << "normal = " << normals[i] << endl;
197     }
198
199     // Calculate texture coordinates
200     point_list geod_nodes;
201     geod_nodes.clear();
202     geod_nodes.reserve(4);
203     int_list rectangle;
204     rectangle.clear();
205     rectangle.reserve(4);
206     for ( i = 0; i < 4; ++i ) {
207         geod_nodes.push_back( geod[i] );
208         rectangle.push_back( i );
209     }
210     point_list texs = calc_tex_coords( b, geod_nodes, rectangle, 
211                                        1000.0 / tex_width );
212
213     // Allocate ssg structure
214     ssgVertexArray   *vl = new ssgVertexArray( 4 );
215     ssgNormalArray   *nl = new ssgNormalArray( 4 );
216     ssgTexCoordArray *tl = new ssgTexCoordArray( 4 );
217     ssgColourArray   *cl = new ssgColourArray( 1 );
218
219     sgVec4 color;
220     sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
221     cl->add( color );
222
223     // sgVec3 *vtlist = new sgVec3 [ 4 ];
224     // t->vec3_ptrs.push_back( vtlist );
225     // sgVec3 *vnlist = new sgVec3 [ 4 ];
226     // t->vec3_ptrs.push_back( vnlist );
227     // sgVec2 *tclist = new sgVec2 [ 4 ];
228     // t->vec2_ptrs.push_back( tclist );
229
230     sgVec2 tmp2;
231     sgVec3 tmp3;
232     for ( i = 0; i < 4; ++i ) {
233         sgSetVec3( tmp3, 
234                    rel[i].x(), rel[i].y(), rel[i].z() );
235         vl->add( tmp3 );
236
237         sgSetVec3( tmp3, 
238                    normals[i].x(), normals[i].y(), normals[i].z() );
239         nl->add( tmp3 );
240
241         sgSetVec2( tmp2, texs[i].x(), texs[i].y());
242         tl->add( tmp2 );
243     }
244     
245     ssgLeaf *leaf = 
246         new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
247
248     leaf->setState( state );
249
250     geometry->addKid( leaf );
251
252     return true;
253 }
254
255
256 static void random_pt_inside_tri( float *res,
257                                   float *n1, float *n2, float *n3 )
258 {
259     double a = sg_random();
260     double b = sg_random();
261     if ( a + b > 1.0 ) {
262         a = 1.0 - a;
263         b = 1.0 - b;
264     }
265     double c = 1 - a - b;
266
267     res[0] = n1[0]*a + n2[0]*b + n3[0]*c;
268     res[1] = n1[1]*a + n2[1]*b + n3[1]*c;
269     res[2] = n1[2]*a + n2[2]*b + n3[2]*c;
270 }
271
272
273 static void gen_random_surface_points( ssgLeaf *leaf, ssgVertexArray *lights,
274                                        double factor ) {
275     int num = leaf->getNumTriangles();
276     if ( num > 0 ) {
277         short int n1, n2, n3;
278         float *p1, *p2, *p3;
279         sgVec3 result;
280
281         // generate a repeatable random seed
282         p1 = leaf->getVertex( 0 );
283         unsigned int seed = (unsigned int)(fabs(p1[0]*100));
284         sg_srandom( seed );
285
286         for ( int i = 0; i < num; ++i ) {
287             leaf->getTriangle( i, &n1, &n2, &n3 );
288             p1 = leaf->getVertex(n1);
289             p2 = leaf->getVertex(n2);
290             p3 = leaf->getVertex(n3);
291             double area = sgTriArea( p1, p2, p3 );
292             double num = area / factor;
293
294             // generate a light point for each unit of area
295             while ( num > 1.0 ) {
296                 random_pt_inside_tri( result, p1, p2, p3 );
297                 lights->add( result );
298                 num -= 1.0;
299             }
300             // for partial units of area, use a zombie door method to
301             // create the proper random chance of a light being created
302             // for this triangle
303             if ( num > 0.0 ) {
304                 if ( sg_random() <= num ) {
305                     // a zombie made it through our door
306                     random_pt_inside_tri( result, p1, p2, p3 );
307                     lights->add( result );
308                 }
309             }
310         }
311     }
312 }
313
314
315 /**
316  * User data for populating leaves when they come in range.
317  */
318 class LeafUserData : public ssgBase
319 {
320 public:
321     bool is_filled_in;
322     ssgLeaf * leaf;
323     FGNewMat * mat;
324     ssgBranch * branch;
325     float sin_lat;
326     float cos_lat;
327     float sin_lon;
328     float cos_lon;
329
330     void setup_triangle( int i );
331 };
332
333
334 /**
335  * User data for populating triangles when they come in range.
336  */
337 class TriUserData : public ssgBase
338 {
339 public:
340   bool is_filled_in;
341   float * p1;
342   float * p2;
343   float * p3;
344     sgVec3 center;
345     double area;
346   FGNewMat::ObjectGroup * object_group;
347   ssgBranch * branch;
348     LeafUserData * leafData;
349   unsigned int seed;
350
351     void fill_in_triangle();
352     void add_object_to_triangle(FGNewMat::Object * object);
353     void makeWorldMatrix (sgMat4 ROT, double hdg_deg );
354 };
355
356
357 /**
358  * Fill in a triangle with randomly-placed objects.
359  *
360  * This method is invoked by a callback when the triangle is in range
361  * but not yet populated.
362  *
363  */
364
365 void TriUserData::fill_in_triangle ()
366 {
367                                 // generate a repeatable random seed
368     sg_srandom(seed);
369
370     int nObjects = object_group->get_object_count();
371
372     for (int i = 0; i < nObjects; i++) {
373       FGNewMat::Object * object = object_group->get_object(i);
374       double num = area / object->get_coverage_m2();
375
376       // place an object each unit of area
377       while ( num > 1.0 ) {
378             add_object_to_triangle(object);
379         num -= 1.0;
380       }
381       // for partial units of area, use a zombie door method to
382       // create the proper random chance of an object being created
383       // for this triangle
384       if ( num > 0.0 ) {
385         if ( sg_random() <= num ) {
386           // a zombie made it through our door
387                 add_object_to_triangle(object);
388         }
389       }
390     }
391 }
392
393 void TriUserData::add_object_to_triangle (FGNewMat::Object * object)
394 {
395     // Set up the random heading if required.
396     double hdg_deg = 0;
397     if (object->get_heading_type() == FGNewMat::Object::HEADING_RANDOM)
398         hdg_deg = sg_random() * 360;
399
400     sgMat4 mat;
401     makeWorldMatrix(mat, hdg_deg);
402
403     ssgTransform * pos = new ssgTransform;
404     pos->setTransform(mat);
405     pos->addKid(object->get_random_model());
406     branch->addKid(pos);
407 }
408
409 void TriUserData::makeWorldMatrix (sgMat4 mat, double hdg_deg )
410 {
411     if (hdg_deg == 0) {
412         mat[0][0] =  leafData->sin_lat * leafData->cos_lon;
413         mat[0][1] =  leafData->sin_lat * leafData->sin_lon;
414         mat[0][2] = -leafData->cos_lat;
415         mat[0][3] =  SG_ZERO;
416
417         mat[1][0] =  -leafData->sin_lon;
418         mat[1][1] =  leafData->cos_lon;
419         mat[1][2] =  SG_ZERO;
420         mat[1][3] =  SG_ZERO;
421     } else {
422         float sin_hdg = sin( hdg_deg * SGD_DEGREES_TO_RADIANS ) ;
423         float cos_hdg = cos( hdg_deg * SGD_DEGREES_TO_RADIANS ) ;
424         mat[0][0] =  cos_hdg * leafData->sin_lat * leafData->cos_lon - sin_hdg * leafData->sin_lon;
425         mat[0][1] =  cos_hdg * leafData->sin_lat * leafData->sin_lon + sin_hdg * leafData->cos_lon;
426         mat[0][2] = -cos_hdg * leafData->cos_lat;
427         mat[0][3] =  SG_ZERO;
428
429         mat[1][0] = -sin_hdg * leafData->sin_lat * leafData->cos_lon - cos_hdg * leafData->sin_lon;
430         mat[1][1] = -sin_hdg * leafData->sin_lat * leafData->sin_lon + cos_hdg * leafData->cos_lon;
431         mat[1][2] =  sin_hdg * leafData->cos_lat;
432         mat[1][3] =  SG_ZERO;
433     }
434
435     mat[2][0] = leafData->cos_lat * leafData->cos_lon;
436     mat[2][1] = leafData->cos_lat * leafData->sin_lon;
437     mat[2][2] = leafData->sin_lat;
438     mat[2][3] = SG_ZERO;
439
440     // translate to random point in triangle
441     sgVec3 result;
442     random_pt_inside_tri(result, p1, p2, p3);
443     sgSubVec3(mat[3], result, center);
444
445     mat[3][3] = SG_ONE ;
446 }
447
448 /**
449  * SSG callback for an in-range triangle of randomly-placed objects.
450  *
451  * This pretraversal callback is attached to a branch that is traversed
452  * only when a triangle is in range.  If the triangle is not currently
453  * populated with randomly-placed objects, this callback will populate
454  * it.
455  *
456  * @param entity The entity to which the callback is attached (not used).
457  * @param mask The entity's traversal mask (not used).
458  * @return Always 1, to allow traversal and culling to continue.
459  */
460 static int
461 tri_in_range_callback (ssgEntity * entity, int mask)
462 {
463   TriUserData * data = (TriUserData *)entity->getUserData();
464   if (!data->is_filled_in) {
465         data->fill_in_triangle();
466     data->is_filled_in = true;
467   }
468   return 1;
469 }
470
471
472 /**
473  * SSG callback for an out-of-range triangle of randomly-placed objects.
474  *
475  * This pretraversal callback is attached to a branch that is traversed
476  * only when a triangle is out of range.  If the triangle is currently
477  * populated with randomly-placed objects, the objects will be removed.
478  *
479  *
480  * @param entity The entity to which the callback is attached (not used).
481  * @param mask The entity's traversal mask (not used).
482  * @return Always 0, to prevent any further traversal or culling.
483  */
484 static int
485 tri_out_of_range_callback (ssgEntity * entity, int mask)
486 {
487   TriUserData * data = (TriUserData *)entity->getUserData();
488   if (data->is_filled_in) {
489     data->branch->removeAllKids();
490     data->is_filled_in = false;
491   }
492   return 0;
493 }
494
495
496 /**
497  * ssgEntity with a dummy bounding sphere, to fool culling.
498  *
499  * This forces the in-range and out-of-range branches to be visited
500  * when appropriate, even if they have no children.  It's ugly, but
501  * it works and seems fairly efficient (since branches can still
502  * be culled when they're out of the view frustum).
503  */
504 class DummyBSphereEntity : public ssgEntity
505 {
506 public:
507   DummyBSphereEntity (float radius)
508   {
509     bsphere.setCenter(0, 0, 0);
510     bsphere.setRadius(radius);
511   }
512   virtual ~DummyBSphereEntity () {}
513   virtual void recalcBSphere () { bsphere_is_invalid = false; }
514   virtual void cull (sgFrustum *f, sgMat4 m, int test_needed) {}
515   virtual void isect (sgSphere *s, sgMat4 m, int test_needed) {}
516   virtual void hot (sgVec3 s, sgMat4 m, int test_needed) {}
517   virtual void los (sgVec3 s, sgMat4 m, int test_needed) {}
518 };
519
520
521 /**
522  * Calculate the bounding radius of a triangle from its center.
523  *
524  * @param center The triangle center.
525  * @param p1 The first point in the triangle.
526  * @param p2 The second point in the triangle.
527  * @param p3 The third point in the triangle.
528  * @return The greatest distance any point lies from the center.
529  */
530 static inline float
531 get_bounding_radius( sgVec3 center, float *p1, float *p2, float *p3)
532 {
533    return sqrt( SG_MAX3( sgDistanceSquaredVec3(center, p1),
534                          sgDistanceSquaredVec3(center, p2),
535                          sgDistanceSquaredVec3(center, p3) ) );
536 }
537
538
539 /**
540  * Set up a triangle for randomly-placed objects.
541  *
542  * No objects will be added unless the triangle comes into range.
543  *
544  */
545
546 void LeafUserData::setup_triangle (int i )
547 {
548     short n1, n2, n3;
549     leaf->getTriangle(i, &n1, &n2, &n3);
550
551     float * p1 = leaf->getVertex(n1);
552     float * p2 = leaf->getVertex(n2);
553     float * p3 = leaf->getVertex(n3);
554
555                                 // Set up a single center point for LOD
556     sgVec3 center;
557     sgSetVec3(center,
558               (p1[0] + p2[0] + p3[0]) / 3.0,
559               (p1[1] + p2[1] + p3[1]) / 3.0,
560               (p1[2] + p2[2] + p3[2]) / 3.0);
561     double area = sgTriArea(p1, p2, p3);
562       
563                                 // maximum radius of an object from center.
564     double bounding_radius = get_bounding_radius(center, p1, p2, p3);
565
566                                 // Set up a transformation to the center
567                                 // point, so that everything else can
568                                 // be specified relative to it.
569     ssgTransform * location = new ssgTransform;
570     sgMat4 TRANS;
571     sgMakeTransMat4(TRANS, center);
572     location->setTransform(TRANS);
573     branch->addKid(location);
574
575                                 // Iterate through all the object types.
576     int num_groups = mat->get_object_group_count();
577     for (int j = 0; j < num_groups; j++) {
578                                 // Look up the random object.
579         FGNewMat::ObjectGroup * group = mat->get_object_group(j);
580
581                                 // Set up the range selector for the entire
582                                 // triangle; note that we use the object
583                                 // range plus the bounding radius here, to
584                                 // allow for objects far from the center.
585         float ranges[] = { 0,
586                           group->get_range_m() + bounding_radius,
587                 SG_MAX };
588         ssgRangeSelector * lod = new ssgRangeSelector;
589         lod->setRanges(ranges, 3);
590         location->addKid(lod);
591
592                                 // Create the in-range and out-of-range
593                                 // branches.
594         ssgBranch * in_range = new ssgBranch;
595         ssgBranch * out_of_range = new ssgBranch;
596
597                                 // Set up the user data for if/when
598                                 // the random objects in this triangle
599                                 // are filled in.
600         TriUserData * data = new TriUserData;
601         data->is_filled_in = false;
602         data->p1 = p1;
603         data->p2 = p2;
604         data->p3 = p3;
605         sgCopyVec3 (data->center, center);
606         data->area = area;
607         data->object_group = group;
608         data->branch = in_range;
609         data->leafData = this;
610         data->seed = (unsigned int)(p1[0] * j);
611
612                                 // Set up the in-range node.
613         in_range->setUserData(data);
614         in_range->setTravCallback(SSG_CALLBACK_PRETRAV,
615                                  tri_in_range_callback);
616         lod->addKid(in_range);
617
618                                 // Set up the out-of-range node.
619         out_of_range->setUserData(data);
620         out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
621                                       tri_out_of_range_callback);
622         out_of_range->addKid(new DummyBSphereEntity(bounding_radius));
623         lod->addKid(out_of_range);
624     }
625 }
626
627 /**
628  * SSG callback for an in-range leaf of randomly-placed objects.
629  *
630  * This pretraversal callback is attached to a branch that is
631  * traversed only when a leaf is in range.  If the leaf is not
632  * currently prepared to be populated with randomly-placed objects,
633  * this callback will prepare it (actual population is handled by
634  * the tri_in_range_callback for individual triangles).
635  *
636  * @param entity The entity to which the callback is attached (not used).
637  * @param mask The entity's traversal mask (not used).
638  * @return Always 1, to allow traversal and culling to continue.
639  */
640 static int
641 leaf_in_range_callback (ssgEntity * entity, int mask)
642 {
643   LeafUserData * data = (LeafUserData *)entity->getUserData();
644
645   if (!data->is_filled_in) {
646                                 // Iterate through all the triangles
647                                 // and populate them.
648     int num_tris = data->leaf->getNumTriangles();
649     for ( int i = 0; i < num_tris; ++i ) {
650             data->setup_triangle(i);
651     }
652     data->is_filled_in = true;
653   }
654   return 1;
655 }
656
657
658 /**
659  * SSG callback for an out-of-range leaf of randomly-placed objects.
660  *
661  * This pretraversal callback is attached to a branch that is
662  * traversed only when a leaf is out of range.  If the leaf is
663  * currently prepared to be populated with randomly-placed objects (or
664  * is actually populated), the objects will be removed.
665  *
666  * @param entity The entity to which the callback is attached (not used).
667  * @param mask The entity's traversal mask (not used).
668  * @return Always 0, to prevent any further traversal or culling.
669  */
670 static int
671 leaf_out_of_range_callback (ssgEntity * entity, int mask)
672 {
673   LeafUserData * data = (LeafUserData *)entity->getUserData();
674   if (data->is_filled_in) {
675     data->branch->removeAllKids();
676     data->is_filled_in = false;
677   }
678   return 0;
679 }
680
681
682 /**
683  * Randomly place objects on a surface.
684  *
685  * The leaf node provides the geometry of the surface, while the
686  * material provides the objects and placement density.  Latitude
687  * and longitude are required so that the objects can be rotated
688  * to the world-up vector.  This function does not actually add
689  * any objects; instead, it attaches an ssgRangeSelector to the
690  * branch with callbacks to generate the objects when needed.
691  *
692  * @param leaf The surface where the objects should be placed.
693  * @param branch The branch that will hold the randomly-placed objects.
694  * @param center The center of the leaf in FlightGear coordinates.
695  * @param material_name The name of the surface's material.
696  */
697 static void
698 gen_random_surface_objects (ssgLeaf *leaf,
699                             ssgBranch *branch,
700                             Point3D * center,
701                             const string &material_name)
702 {
703                                 // If the surface has no triangles, return
704                                 // now.
705     int num_tris = leaf->getNumTriangles();
706     if (num_tris < 1)
707       return;
708
709                                 // Get the material for this surface.
710     FGNewMat * mat = material_lib.find(material_name);
711     if (mat == 0) {
712       SG_LOG(SG_INPUT, SG_ALERT, "Unknown material " << material_name);
713       return;
714     }
715
716                                 // If the material has no randomly-placed
717                                 // objects, return now.
718     if (mat->get_object_group_count() < 1)
719       return;
720
721                                 // Calculate the geodetic centre of
722                                 // the tile, for aligning automatic
723                                 // objects.
724     double lon_deg, lat_rad, lat_deg, alt_m, sl_radius_m;
725     Point3D geoc = sgCartToPolar3d(*center);
726     lon_deg = geoc.lon() * SGD_RADIANS_TO_DEGREES;
727     sgGeocToGeod(geoc.lat(), geoc.radius(),
728                  &lat_rad, &alt_m, &sl_radius_m);
729     lat_deg = lat_rad * SGD_RADIANS_TO_DEGREES;
730
731                                 // LOD for the leaf
732                                 // max random object range: 20000m
733     float ranges[] = { 0, 20000, 1000000 };
734     ssgRangeSelector * lod = new ssgRangeSelector;
735     lod->setRanges(ranges, 3);
736     branch->addKid(lod);
737
738                                 // Create the in-range and out-of-range
739                                 // branches.
740     ssgBranch * in_range = new ssgBranch;
741     ssgBranch * out_of_range = new ssgBranch;
742     lod->addKid(in_range);
743     lod->addKid(out_of_range);
744
745     LeafUserData * data = new LeafUserData;
746     data->is_filled_in = false;
747     data->leaf = leaf;
748     data->mat = mat;
749     data->branch = in_range;
750     data->sin_lat = sin(lat_deg * SGD_DEGREES_TO_RADIANS);
751     data->cos_lat = cos(lat_deg * SGD_DEGREES_TO_RADIANS);
752     data->sin_lon = sin(lon_deg * SGD_DEGREES_TO_RADIANS);
753     data->cos_lon = cos(lon_deg * SGD_DEGREES_TO_RADIANS);
754
755     in_range->setUserData(data);
756     in_range->setTravCallback(SSG_CALLBACK_PRETRAV, leaf_in_range_callback);
757     out_of_range->setUserData(data);
758     out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
759                                    leaf_out_of_range_callback);
760     out_of_range
761       ->addKid(new DummyBSphereEntity(leaf->getBSphere()->getRadius()));
762 }
763
764
765 \f
766 ////////////////////////////////////////////////////////////////////////
767 // Scenery loaders.
768 ////////////////////////////////////////////////////////////////////////
769
770
771 // Load an Ascii obj file
772 ssgBranch *fgAsciiObjLoad( const string& path, FGTileEntry *t,
773                            ssgVertexArray *lights, const bool is_base)
774 {
775     FGNewMat *newmat = NULL;
776     string material;
777     float coverage = -1;
778     Point3D pp;
779     // sgVec3 approx_normal;
780     // double normal[3], scale = 0.0;
781     // double x, y, z, xmax, xmin, ymax, ymin, zmax, zmin;
782     // GLfloat sgenparams[] = { 1.0, 0.0, 0.0, 0.0 };
783     // GLint display_list = 0;
784     int shading;
785     bool in_faces = false;
786     int vncount, vtcount;
787     int n1 = 0, n2 = 0, n3 = 0;
788     int tex;
789     // int last1 = 0, last2 = 0;
790     bool odd = false;
791     point_list nodes;
792     Point3D node;
793     Point3D center;
794     double scenery_version = 0.0;
795     double tex_width = 1000.0, tex_height = 1000.0;
796     bool shared_done = false;
797     int_list fan_vertices;
798     int_list fan_tex_coords;
799     int i;
800     ssgSimpleState *state = NULL;
801     sgVec3 *vtlist, *vnlist;
802     sgVec2 *tclist;
803
804     ssgBranch *tile = new ssgBranch () ;
805
806     tile -> setName ( (char *)path.c_str() ) ;
807
808     // Attempt to open "path.gz" or "path"
809     sg_gzifstream in( path );
810     if ( ! in.is_open() ) {
811         SG_LOG( SG_TERRAIN, SG_DEBUG, "Cannot open file: " << path );
812         SG_LOG( SG_TERRAIN, SG_DEBUG, "default to ocean tile: " << path );
813
814         delete tile;
815
816         return NULL;
817     }
818
819     shading = fgGetBool("/sim/rendering/shading");
820
821     if ( is_base ) {
822         t->ncount = 0;
823     }
824     vncount = 0;
825     vtcount = 0;
826     if ( is_base ) {
827         t->bounding_radius = 0.0;
828     }
829     center = t->center;
830
831     // StopWatch stopwatch;
832     // stopwatch.start();
833
834     // ignore initial comments and blank lines. (priming the pump)
835     // in >> skipcomment;
836     // string line;
837
838     string token;
839     char c;
840
841 #ifdef __MWERKS__
842     while ( in.get(c) && c  != '\0' ) {
843         in.putback(c);
844 #else
845     while ( ! in.eof() ) {
846 #endif
847         in >> ::skipws;
848
849         if ( in.get( c ) && c == '#' ) {
850             // process a comment line
851
852             // getline( in, line );
853             // cout << "comment = " << line << endl;
854
855             in >> token;
856
857             if ( token == "Version" ) {
858                 // read scenery versions number
859                 in >> scenery_version;
860                 // cout << "scenery_version = " << scenery_version << endl;
861                 if ( scenery_version > 0.4 ) {
862                     SG_LOG( SG_TERRAIN, SG_ALERT, 
863                             "\nYou are attempting to load a tile format that\n"
864                             << "is newer than this version of flightgear can\n"
865                             << "handle.  You should upgrade your copy of\n"
866                             << "FlightGear to the newest version.  For\n"
867                             << "details, please see:\n"
868                             << "\n    http://www.flightgear.org\n" );
869                     exit(-1);
870                 }
871             } else if ( token == "gbs" ) {
872                 // reference point (center offset)
873                 if ( is_base ) {
874                     in >> t->center >> t->bounding_radius;
875                 } else {
876                     Point3D junk1;
877                     double junk2;
878                     in >> junk1 >> junk2;
879                 }
880                 center = t->center;
881                 // cout << "center = " << center 
882                 //      << " radius = " << t->bounding_radius << endl;
883             } else if ( token == "bs" ) {
884                 // reference point (center offset)
885                 // (skip past this)
886                 Point3D junk1;
887                 double junk2;
888                 in >> junk1 >> junk2;
889             } else if ( token == "usemtl" ) {
890                 // material property specification
891
892                 // if first usemtl with shared_done = false, then set
893                 // shared_done true and build the ssg shared lists
894                 if ( ! shared_done ) {
895                     // sanity check
896                     if ( (int)nodes.size() != vncount ) {
897                         SG_LOG( SG_TERRAIN, SG_ALERT, 
898                                 "Tile has mismatched nodes = " << nodes.size()
899                                 << " and normals = " << vncount << " : " 
900                                 << path );
901                         // exit(-1);
902                     }
903                     shared_done = true;
904
905                     vtlist = new sgVec3 [ nodes.size() ];
906                     t->vec3_ptrs.push_back( vtlist );
907                     vnlist = new sgVec3 [ vncount ];
908                     t->vec3_ptrs.push_back( vnlist );
909                     tclist = new sgVec2 [ vtcount ];
910                     t->vec2_ptrs.push_back( tclist );
911
912                     for ( i = 0; i < (int)nodes.size(); ++i ) {
913                         sgSetVec3( vtlist[i], 
914                                    nodes[i][0], nodes[i][1], nodes[i][2] );
915                     }
916                     for ( i = 0; i < vncount; ++i ) {
917                         sgSetVec3( vnlist[i], 
918                                    normals[i][0], 
919                                    normals[i][1],
920                                    normals[i][2] );
921                     }
922                     for ( i = 0; i < vtcount; ++i ) {
923                         sgSetVec2( tclist[i],
924                                    tex_coords[i][0],
925                                    tex_coords[i][1] );
926                     }
927                 }
928
929                 // display_list = xglGenLists(1);
930                 // xglNewList(display_list, GL_COMPILE);
931                 // printf("xglGenLists(); xglNewList();\n");
932                 in_faces = false;
933
934                 // scan the material line
935                 in >> material;
936                 
937                 // find this material in the properties list
938
939                 newmat = material_lib.find( material );
940                 if ( newmat == NULL ) {
941                     // see if this is an on the fly texture
942                     string file = path;
943                     int pos = file.rfind( "/" );
944                     file = file.substr( 0, pos );
945                     // cout << "current file = " << file << endl;
946                     file += "/";
947                     file += material;
948                     // cout << "current file = " << file << endl;
949                     if ( ! material_lib.add_item( file ) ) {
950                         SG_LOG( SG_TERRAIN, SG_ALERT, 
951                                 "Ack! unknown usemtl name = " << material 
952                                 << " in " << path );
953                     } else {
954                         // locate our newly created material
955                         newmat = material_lib.find( material );
956                         if ( newmat == NULL ) {
957                             SG_LOG( SG_TERRAIN, SG_ALERT, 
958                                     "Ack! bad on the fly materia create = "
959                                     << material << " in " << path );
960                         }
961                     }
962                 }
963
964                 if ( newmat != NULL ) {
965                     // set the texture width and height values for this
966                     // material
967                     tex_width = newmat->get_xsize();
968                     tex_height = newmat->get_ysize();
969                     state = newmat->get_state();
970                     coverage = newmat->get_light_coverage();
971                     // cout << "(w) = " << tex_width << " (h) = "
972                     //      << tex_width << endl;
973                 } else {
974                     coverage = -1;
975                 }
976             } else {
977                 // unknown comment, just gobble the input until the
978                 // end of line
979
980                 in >> skipeol;
981             }
982         } else {
983             in.putback( c );
984         
985             in >> token;
986
987             // cout << "token = " << token << endl;
988
989             if ( token == "vn" ) {
990                 // vertex normal
991                 if ( vncount < FG_MAX_NODES ) {
992                     in >> normals[vncount][0]
993                        >> normals[vncount][1]
994                        >> normals[vncount][2];
995                     vncount++;
996                 } else {
997                     SG_LOG( SG_TERRAIN, SG_ALERT, 
998                             "Read too many vertex normals in " << path 
999                             << " ... dying :-(" );
1000                     exit(-1);
1001                 }
1002             } else if ( token == "vt" ) {
1003                 // vertex texture coordinate
1004                 if ( vtcount < FG_MAX_NODES*3 ) {
1005                     in >> tex_coords[vtcount][0]
1006                        >> tex_coords[vtcount][1];
1007                     vtcount++;
1008                 } else {
1009                     SG_LOG( SG_TERRAIN, SG_ALERT, 
1010                             "Read too many vertex texture coords in " << path
1011                             << " ... dying :-("
1012                             );
1013                     exit(-1);
1014                 }
1015             } else if ( token == "v" ) {
1016                 // node (vertex)
1017                 if ( t->ncount < FG_MAX_NODES ) {
1018                     /* in >> nodes[t->ncount][0]
1019                        >> nodes[t->ncount][1]
1020                        >> nodes[t->ncount][2]; */
1021                     in >> node;
1022                     nodes.push_back(node);
1023                     if ( is_base ) {
1024                         t->ncount++;
1025                     }
1026                 } else {
1027                     SG_LOG( SG_TERRAIN, SG_ALERT, 
1028                             "Read too many nodes in " << path 
1029                             << " ... dying :-(");
1030                     exit(-1);
1031                 }
1032             } else if ( (token == "tf") || (token == "ts") || (token == "f") ) {
1033                 // triangle fan, strip, or individual face
1034                 // SG_LOG( SG_TERRAIN, SG_INFO, "new fan or strip");
1035
1036                 fan_vertices.clear();
1037                 fan_tex_coords.clear();
1038                 odd = true;
1039
1040                 // xglBegin(GL_TRIANGLE_FAN);
1041
1042                 in >> n1;
1043                 fan_vertices.push_back( n1 );
1044                 // xglNormal3dv(normals[n1]);
1045                 if ( in.get( c ) && c == '/' ) {
1046                     in >> tex;
1047                     fan_tex_coords.push_back( tex );
1048                     if ( scenery_version >= 0.4 ) {
1049                         if ( tex_width > 0 ) {
1050                             tclist[tex][0] *= (1000.0 / tex_width);
1051                         }
1052                         if ( tex_height > 0 ) {
1053                             tclist[tex][1] *= (1000.0 / tex_height);
1054                         }
1055                     }
1056                     pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1057                     pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1058                 } else {
1059                     in.putback( c );
1060                     pp = local_calc_tex_coords(nodes[n1], center);
1061                 }
1062                 // xglTexCoord2f(pp.x(), pp.y());
1063                 // xglVertex3dv(nodes[n1].get_n());
1064
1065                 in >> n2;
1066                 fan_vertices.push_back( n2 );
1067                 // xglNormal3dv(normals[n2]);
1068                 if ( in.get( c ) && c == '/' ) {
1069                     in >> tex;
1070                     fan_tex_coords.push_back( tex );
1071                     if ( scenery_version >= 0.4 ) {
1072                         if ( tex_width > 0 ) {
1073                             tclist[tex][0] *= (1000.0 / tex_width);
1074                         }
1075                         if ( tex_height > 0 ) {
1076                             tclist[tex][1] *= (1000.0 / tex_height);
1077                         }
1078                     }
1079                     pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1080                     pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1081                 } else {
1082                     in.putback( c );
1083                     pp = local_calc_tex_coords(nodes[n2], center);
1084                 }
1085                 // xglTexCoord2f(pp.x(), pp.y());
1086                 // xglVertex3dv(nodes[n2].get_n());
1087                 
1088                 // read all subsequent numbers until next thing isn't a number
1089                 while ( true ) {
1090                     in >> ::skipws;
1091
1092                     char c;
1093                     in.get(c);
1094                     in.putback(c);
1095                     if ( ! isdigit(c) || in.eof() ) {
1096                         break;
1097                     }
1098
1099                     in >> n3;
1100                     fan_vertices.push_back( n3 );
1101                     // cout << "  triangle = "
1102                     //      << n1 << "," << n2 << "," << n3
1103                     //      << endl;
1104                     // xglNormal3dv(normals[n3]);
1105                     if ( in.get( c ) && c == '/' ) {
1106                         in >> tex;
1107                         fan_tex_coords.push_back( tex );
1108                         if ( scenery_version >= 0.4 ) {
1109                             if ( tex_width > 0 ) {
1110                                 tclist[tex][0] *= (1000.0 / tex_width);
1111                             }
1112                             if ( tex_height > 0 ) {
1113                                 tclist[tex][1] *= (1000.0 / tex_height);
1114                             }
1115                         }
1116                         pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1117                         pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1118                     } else {
1119                         in.putback( c );
1120                         pp = local_calc_tex_coords(nodes[n3], center);
1121                     }
1122                     // xglTexCoord2f(pp.x(), pp.y());
1123                     // xglVertex3dv(nodes[n3].get_n());
1124
1125                     if ( (token == "tf") || (token == "f") ) {
1126                         // triangle fan
1127                         n2 = n3;
1128                     } else {
1129                         // triangle strip
1130                         odd = !odd;
1131                         n1 = n2;
1132                         n2 = n3;
1133                     }
1134                 }
1135
1136                 // xglEnd();
1137
1138                 // build the ssg entity
1139                 int size = (int)fan_vertices.size();
1140                 ssgVertexArray   *vl = new ssgVertexArray( size );
1141                 ssgNormalArray   *nl = new ssgNormalArray( size );
1142                 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1143                 ssgColourArray   *cl = new ssgColourArray( 1 );
1144
1145                 sgVec4 color;
1146                 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
1147                 cl->add( color );
1148
1149                 sgVec2 tmp2;
1150                 sgVec3 tmp3;
1151                 for ( i = 0; i < size; ++i ) {
1152                     sgCopyVec3( tmp3, vtlist[ fan_vertices[i] ] );
1153                     vl -> add( tmp3 );
1154
1155                     sgCopyVec3( tmp3, vnlist[ fan_vertices[i] ] );
1156                     nl -> add( tmp3 );
1157
1158                     sgCopyVec2( tmp2, tclist[ fan_tex_coords[i] ] );
1159                     tl -> add( tmp2 );
1160                 }
1161
1162                 ssgLeaf *leaf = NULL;
1163                 if ( token == "tf" ) {
1164                     // triangle fan
1165                     leaf = 
1166                         new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
1167                 } else if ( token == "ts" ) {
1168                     // triangle strip
1169                     leaf = 
1170                         new ssgVtxTable ( GL_TRIANGLE_STRIP, vl, nl, tl, cl );
1171                 } else if ( token == "f" ) {
1172                     // triangle
1173                     leaf = 
1174                         new ssgVtxTable ( GL_TRIANGLES, vl, nl, tl, cl );
1175                 }
1176                 // leaf->makeDList();
1177                 leaf->setState( state );
1178
1179                 tile->addKid( leaf );
1180
1181                 if ( is_base ) {
1182                     if ( coverage > 0.0 ) {
1183                         if ( coverage < 10000.0 ) {
1184                             SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1185                                    << coverage << ", pushing up to 10000");
1186                             coverage = 10000;
1187                         }
1188                         gen_random_surface_points(leaf, lights, coverage);
1189                     }
1190                 }
1191             } else {
1192                 SG_LOG( SG_TERRAIN, SG_WARN, "Unknown token in " 
1193                         << path << " = " << token );
1194             }
1195
1196             // eat white space before start of while loop so if we are
1197             // done with useful input it is noticed before hand.
1198             in >> ::skipws;
1199         }
1200     }
1201
1202     if ( is_base ) {
1203         t->nodes = nodes;
1204     }
1205
1206     // stopwatch.stop();
1207     // SG_LOG( SG_TERRAIN, SG_DEBUG, 
1208     //     "Loaded " << path << " in " 
1209     //     << stopwatch.elapsedSeconds() << " seconds" );
1210
1211     return tile;
1212 }
1213
1214
1215 ssgLeaf *gen_leaf( const string& path,
1216                    const GLenum ty, const string& material,
1217                    const point_list& nodes, const point_list& normals,
1218                    const point_list& texcoords,
1219                    const int_list& node_index,
1220                    const int_list& normal_index,
1221                    const int_list& tex_index,
1222                    const bool calc_lights, ssgVertexArray *lights )
1223 {
1224     double tex_width = 1000.0, tex_height = 1000.0;
1225     ssgSimpleState *state = NULL;
1226     float coverage = -1;
1227
1228     FGNewMat *newmat = material_lib.find( material );
1229     if ( newmat == NULL ) {
1230         // see if this is an on the fly texture
1231         string file = path;
1232         string::size_type pos = file.rfind( "/" );
1233         file = file.substr( 0, pos );
1234         // cout << "current file = " << file << endl;
1235         file += "/";
1236         file += material;
1237         // cout << "current file = " << file << endl;
1238         if ( ! material_lib.add_item( file ) ) {
1239             SG_LOG( SG_TERRAIN, SG_ALERT, 
1240                     "Ack! unknown usemtl name = " << material 
1241                     << " in " << path );
1242         } else {
1243             // locate our newly created material
1244             newmat = material_lib.find( material );
1245             if ( newmat == NULL ) {
1246                 SG_LOG( SG_TERRAIN, SG_ALERT, 
1247                         "Ack! bad on the fly material create = "
1248                         << material << " in " << path );
1249             }
1250         }
1251     }
1252
1253     if ( newmat != NULL ) {
1254         // set the texture width and height values for this
1255         // material
1256         tex_width = newmat->get_xsize();
1257         tex_height = newmat->get_ysize();
1258         state = newmat->get_state();
1259         coverage = newmat->get_light_coverage();
1260         // cout << "(w) = " << tex_width << " (h) = "
1261         //      << tex_width << endl;
1262     } else {
1263         coverage = -1;
1264     }
1265
1266     sgVec2 tmp2;
1267     sgVec3 tmp3;
1268     sgVec4 tmp4;
1269     int i;
1270
1271     // vertices
1272     int size = node_index.size();
1273     if ( size < 1 ) {
1274         SG_LOG( SG_TERRAIN, SG_ALERT, "Woh! node list size < 1" );
1275         exit(-1);
1276     }
1277     ssgVertexArray *vl = new ssgVertexArray( size );
1278     Point3D node;
1279     for ( i = 0; i < size; ++i ) {
1280         node = nodes[ node_index[i] ];
1281         sgSetVec3( tmp3, node[0], node[1], node[2] );
1282         vl -> add( tmp3 );
1283     }
1284
1285     // normals
1286     Point3D normal;
1287     ssgNormalArray *nl = new ssgNormalArray( size );
1288     if ( normal_index.size() ) {
1289         // object file specifies normal indices (i.e. normal indices
1290         // aren't 'implied'
1291         for ( i = 0; i < size; ++i ) {
1292             normal = normals[ normal_index[i] ];
1293             sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1294             nl -> add( tmp3 );
1295         }
1296     } else {
1297         // use implied normal indices.  normal index = vertex index.
1298         for ( i = 0; i < size; ++i ) {
1299             normal = normals[ node_index[i] ];
1300             sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1301             nl -> add( tmp3 );
1302         }
1303     }
1304
1305     // colors
1306     ssgColourArray *cl = new ssgColourArray( 1 );
1307     sgSetVec4( tmp4, 1.0, 1.0, 1.0, 1.0 );
1308     cl->add( tmp4 );
1309
1310     // texture coordinates
1311     size = tex_index.size();
1312     Point3D texcoord;
1313     ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1314     if ( size == 1 ) {
1315         texcoord = texcoords[ tex_index[0] ];
1316         sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1317         sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1318         if ( tex_width > 0 ) {
1319             tmp2[0] *= (1000.0 / tex_width);
1320         }
1321         if ( tex_height > 0 ) {
1322             tmp2[1] *= (1000.0 / tex_height);
1323         }
1324         tl -> add( tmp2 );
1325     } else if ( size > 1 ) {
1326         for ( i = 0; i < size; ++i ) {
1327             texcoord = texcoords[ tex_index[i] ];
1328             sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1329             if ( tex_width > 0 ) {
1330                 tmp2[0] *= (1000.0 / tex_width);
1331             }
1332             if ( tex_height > 0 ) {
1333                 tmp2[1] *= (1000.0 / tex_height);
1334             }
1335             tl -> add( tmp2 );
1336         }
1337     }
1338
1339     ssgLeaf *leaf = new ssgVtxTable ( ty, vl, nl, tl, cl );
1340
1341     // lookup the state record
1342
1343     leaf->setState( state );
1344
1345     if ( calc_lights ) {
1346         if ( coverage > 0.0 ) {
1347             if ( coverage < 10000.0 ) {
1348                 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1349                        << coverage << ", pushing up to 10000");
1350                 coverage = 10000;
1351             }
1352             gen_random_surface_points(leaf, lights, coverage);
1353         }
1354     }
1355
1356     return leaf;
1357 }
1358
1359
1360 // Load an Binary obj file
1361 bool fgBinObjLoad( const string& path, const bool is_base,
1362                    Point3D *center,
1363                    double *bounding_radius,
1364                    ssgBranch* geometry,
1365                    ssgBranch* rwy_lights,
1366                    ssgVertexArray *ground_lights )
1367 {
1368     SGBinObject obj;
1369     bool use_random_objects =
1370       fgGetBool("/sim/rendering/random-objects", true);
1371
1372     if ( ! obj.read_bin( path ) ) {
1373         return false;
1374     }
1375
1376     geometry->setName( (char *)path.c_str() );
1377
1378     if ( is_base ) {
1379         // reference point (center offset/bounding sphere)
1380         *center = obj.get_gbs_center();
1381         *bounding_radius = obj.get_gbs_radius();
1382
1383     }
1384
1385     point_list const& nodes = obj.get_wgs84_nodes();
1386     point_list const& colors = obj.get_colors();
1387     point_list const& normals = obj.get_normals();
1388     point_list const& texcoords = obj.get_texcoords();
1389
1390     string material;
1391     int_list tex_index;
1392
1393     group_list::size_type i;
1394     bool is_lighting = false;
1395
1396     // generate points
1397     string_list const& pt_materials = obj.get_pt_materials();
1398     group_list const& pts_v = obj.get_pts_v();
1399     group_list const& pts_n = obj.get_pts_n();
1400     for ( i = 0; i < pts_v.size(); ++i ) {
1401         // cout << "pts_v.size() = " << pts_v.size() << endl;
1402         if ( pt_materials[i].substr(0, 3) == "RWY" ) {
1403             material = "LIGHTS";
1404             is_lighting = true;
1405         } else {
1406             material = pt_materials[i];
1407         }
1408         tex_index.clear();
1409         ssgLeaf *leaf = gen_leaf( path, GL_POINTS, material,
1410                                   nodes, normals, texcoords,
1411                                   pts_v[i], pts_n[i], tex_index,
1412                                   false, ground_lights );
1413
1414         if ( is_lighting ) {
1415             float ranges[] = {
1416                 0,
1417                 12000
1418             };
1419             leaf->setCallback(SSG_CALLBACK_PREDRAW, runway_lights_predraw);
1420             ssgRangeSelector * lod = new ssgRangeSelector;
1421             lod->setRanges(ranges, 2);
1422             lod->addKid(leaf);
1423             rwy_lights->addKid(lod);
1424         } else {
1425             geometry->addKid( leaf );
1426         }
1427     }
1428
1429     // Put all randomly-placed objects under a separate branch
1430     // (actually an ssgRangeSelector) named "random-models".
1431     ssgBranch * random_object_branch = 0;
1432     if (use_random_objects) {
1433         float ranges[] = { 0, 20000 }; // Maximum 20km range for random objects
1434       ssgRangeSelector * object_lod = new ssgRangeSelector;
1435       object_lod->setRanges(ranges, 2);
1436       object_lod->setName("random-models");
1437       geometry->addKid(object_lod);
1438       random_object_branch = new ssgBranch;
1439       object_lod->addKid(random_object_branch);
1440     }
1441
1442     // generate triangles
1443     string_list const& tri_materials = obj.get_tri_materials();
1444     group_list const& tris_v = obj.get_tris_v();
1445     group_list const& tris_n = obj.get_tris_n();
1446     group_list const& tris_tc = obj.get_tris_tc();
1447     for ( i = 0; i < tris_v.size(); ++i ) {
1448         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLES, tri_materials[i],
1449                                   nodes, normals, texcoords,
1450                                   tris_v[i], tris_n[i], tris_tc[i],
1451                                   is_base, ground_lights );
1452
1453         if (use_random_objects)
1454           gen_random_surface_objects(leaf, random_object_branch,
1455                                      center, tri_materials[i]);
1456         geometry->addKid( leaf );
1457     }
1458
1459     // generate strips
1460     string_list const& strip_materials = obj.get_strip_materials();
1461     group_list const& strips_v = obj.get_strips_v();
1462     group_list const& strips_n = obj.get_strips_n();
1463     group_list const& strips_tc = obj.get_strips_tc();
1464     for ( i = 0; i < strips_v.size(); ++i ) {
1465         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_STRIP, strip_materials[i],
1466                                   nodes, normals, texcoords,
1467                                   strips_v[i], strips_n[i], strips_tc[i],
1468                                   is_base, ground_lights );
1469
1470         if (use_random_objects)
1471           gen_random_surface_objects(leaf, random_object_branch,
1472                                      center,strip_materials[i]);
1473         geometry->addKid( leaf );
1474     }
1475
1476     // generate fans
1477     string_list const& fan_materials = obj.get_fan_materials();
1478     group_list const& fans_v = obj.get_fans_v();
1479     group_list const& fans_n = obj.get_fans_n();
1480     group_list const& fans_tc = obj.get_fans_tc();
1481     for ( i = 0; i < fans_v.size(); ++i ) {
1482         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_FAN, fan_materials[i],
1483                                   nodes, normals, texcoords,
1484                                   fans_v[i], fans_n[i], fans_tc[i],
1485                                   is_base, ground_lights );
1486         if (use_random_objects)
1487           gen_random_surface_objects(leaf, random_object_branch,
1488                                      center, fan_materials[i]);
1489         geometry->addKid( leaf );
1490     }
1491
1492     return true;
1493 }