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