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