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