]> git.mxchange.org Git - flightgear.git/blob - src/Objects/obj.cxx
Detabified for Norman Vine.
[flightgear.git] / src / Objects / obj.cxx
1 // obj.cxx -- routines to handle "sorta" WaveFront .obj format files.
2 //
3 // Written by Curtis Olson, started October 1997.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - curt@infoplane.com
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #ifdef SG_MATH_EXCEPTION_CLASH
29 #  include <math.h>
30 #endif
31
32 #include <stdio.h>
33 #include <string.h>
34
35 #include <simgear/compiler.h>
36 #include <simgear/sg_inlines.h>
37 #include <simgear/io/sg_binobj.hxx>
38
39 #include STL_STRING
40 #include <map>                  // STL
41 #include <vector>               // STL
42 #include <ctype.h>              // isdigit()
43
44 #include <simgear/constants.h>
45 #include <simgear/debug/logstream.hxx>
46 #include <simgear/math/point3d.hxx>
47 #include <simgear/math/polar3d.hxx>
48 #include <simgear/math/sg_geodesy.hxx>
49 #include <simgear/math/sg_random.h>
50 #include <simgear/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  * 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   DummyBSphereEntity (float radius)
539   {
540     bsphere.setCenter(0, 0, 0);
541     bsphere.setRadius(radius);
542   }
543   virtual ~DummyBSphereEntity () {}
544   virtual void recalcBSphere () { bsphere_is_invalid = false; }
545   virtual void cull (sgFrustum *f, sgMat4 m, int test_needed) {}
546   virtual void isect (sgSphere *s, sgMat4 m, int test_needed) {}
547   virtual void hot (sgVec3 s, sgMat4 m, int test_needed) {}
548   virtual void los (sgVec3 s, sgMat4 m, int test_needed) {}
549 };
550
551
552 /**
553  * Calculate the bounding radius of a triangle from its center.
554  *
555  * @param center The triangle center.
556  * @param p1 The first point in the triangle.
557  * @param p2 The second point in the triangle.
558  * @param p3 The third point in the triangle.
559  * @return The greatest distance any point lies from the center.
560  */
561 static inline float
562 get_bounding_radius( sgVec3 center, float *p1, float *p2, float *p3)
563 {
564    return sqrt( SG_MAX3( sgDistanceSquaredVec3(center, p1),
565                          sgDistanceSquaredVec3(center, p2),
566                          sgDistanceSquaredVec3(center, p3) ) );
567 }
568
569
570 /**
571  * Set up a triangle for randomly-placed objects.
572  *
573  * No objects will be added unless the triangle comes into range.
574  *
575  * @param leaf The leaf containing the data for the terrain surface.
576  * @param tri_index The index of the triangle in the leaf.
577  * @param mat The material data for the triangle.
578  * @param branch The branch to which the randomly-placed objects
579  *        should be added.
580  * @param lon_deg The longitude of the surface center, in degrees.
581  * @param lat_deg The latitude of the surface center, in degrees.
582  */
583 static void
584 setup_triangle (float * p1, float * p2, float * p3,
585                 FGNewMat * mat, ssgBranch * branch,
586                 double lon_deg, double lat_deg)
587 {
588                                 // Set up a single center point for LOD
589     sgVec3 center;
590     sgSetVec3(center,
591               (p1[0] + p2[0] + p3[0]) / 3.0,
592               (p1[1] + p2[1] + p3[1]) / 3.0,
593               (p1[2] + p2[2] + p3[2]) / 3.0);
594       
595                                 // maximum radius of an object from center.
596     double bounding_radius = get_bounding_radius(center, p1, p2, p3);
597
598                                 // Set up a transformation to the center
599                                 // point, so that everything else can
600                                 // be specified relative to it.
601     ssgTransform * location = new ssgTransform;
602     sgMat4 TRANS;
603     sgMakeTransMat4(TRANS, center);
604     location->setTransform(TRANS);
605     branch->addKid(location);
606
607                                 // Iterate through all the object types.
608     int num_groups = mat->get_object_group_count();
609     for (int i = 0; i < num_groups; i++) {
610                                 // Look up the random object.
611         FGNewMat::ObjectGroup * group = mat->get_object_group(i);
612
613                                 // Set up the range selector for the entire
614                                 // triangle; note that we use the object
615                                 // range plus the bounding radius here, to
616                                 // allow for objects far from the center.
617         float ranges[] = {0,
618                           group->get_range_m() + bounding_radius,
619                           SG_MAX};
620         ssgRangeSelector * lod = new ssgRangeSelector;
621         lod->setRanges(ranges, 3);
622         location->addKid(lod);
623
624                                 // Create the in-range and out-of-range
625                                 // branches.
626         ssgBranch * in_range = new ssgBranch;
627         ssgBranch * out_of_range = new ssgBranch;
628
629                                 // Set up the user data for if/when
630                                 // the random objects in this triangle
631                                 // are filled in.
632         TriUserData * data = new TriUserData;
633         data->is_filled_in = false;
634         data->p1 = p1;
635         data->p2 = p2;
636         data->p3 = p3;
637         data->object_group = group;
638         data->branch = in_range;
639         data->lon_deg = lon_deg;
640         data->lat_deg = lat_deg;
641         data->seed = (unsigned int)((p1[0] + lon_deg + lat_deg) * i * 128);
642
643                                 // Set up the in-range node.
644         in_range->setUserData(data);
645         in_range->setTravCallback(SSG_CALLBACK_PRETRAV,
646                                  tri_in_range_callback);
647         lod->addKid(in_range);
648
649                                 // Set up the out-of-range node.
650         out_of_range->setUserData(data);
651         out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
652                                       tri_out_of_range_callback);
653         out_of_range->addKid(new DummyBSphereEntity(bounding_radius));
654         lod->addKid(out_of_range);
655     }
656 }
657
658
659 /**
660  * User data for populating leaves when they come in range.
661  */
662 class LeafUserData : public ssgBase
663 {
664 public:
665   bool is_filled_in;
666   ssgLeaf * leaf;
667   FGNewMat * mat;
668   ssgBranch * branch;
669   double lon_deg;
670   double lat_deg;
671 };
672
673
674 /**
675  * SSG callback for an in-range leaf of randomly-placed objects.
676  *
677  * This pretraversal callback is attached to a branch that is
678  * traversed only when a leaf is in range.  If the leaf is not
679  * currently prepared to be populated with randomly-placed objects,
680  * this callback will prepare it (actual population is handled by
681  * the tri_in_range_callback for individual triangles).
682  *
683  * @param entity The entity to which the callback is attached (not used).
684  * @param mask The entity's traversal mask (not used).
685  * @return Always 1, to allow traversal and culling to continue.
686  */
687 static int
688 leaf_in_range_callback (ssgEntity * entity, int mask)
689 {
690   LeafUserData * data = (LeafUserData *)entity->getUserData();
691
692   if (!data->is_filled_in) {
693                                 // Iterate through all the triangles
694                                 // and populate them.
695     int num_tris = data->leaf->getNumTriangles();
696     for ( int i = 0; i < num_tris; ++i ) {
697       short n1, n2, n3;
698       data->leaf->getTriangle(i, &n1, &n2, &n3);
699       setup_triangle(data->leaf->getVertex(n1),
700                      data->leaf->getVertex(n2),
701                      data->leaf->getVertex(n3),
702                      data->mat, data->branch, data->lon_deg, data->lat_deg);
703     }
704     data->is_filled_in = true;
705   }
706   return 1;
707 }
708
709
710 /**
711  * SSG callback for an out-of-range leaf of randomly-placed objects.
712  *
713  * This pretraversal callback is attached to a branch that is
714  * traversed only when a leaf is out of range.  If the leaf is
715  * currently prepared to be populated with randomly-placed objects (or
716  * is actually populated), the objects will be removed.
717  *
718  * @param entity The entity to which the callback is attached (not used).
719  * @param mask The entity's traversal mask (not used).
720  * @return Always 0, to prevent any further traversal or culling.
721  */
722 static int
723 leaf_out_of_range_callback (ssgEntity * entity, int mask)
724 {
725   LeafUserData * data = (LeafUserData *)entity->getUserData();
726   if (data->is_filled_in) {
727     data->branch->removeAllKids();
728     data->is_filled_in = false;
729   }
730   return 0;
731 }
732
733
734 /**
735  * Randomly place objects on a surface.
736  *
737  * The leaf node provides the geometry of the surface, while the
738  * material provides the objects and placement density.  Latitude
739  * and longitude are required so that the objects can be rotated
740  * to the world-up vector.  This function does not actually add
741  * any objects; instead, it attaches an ssgRangeSelector to the
742  * branch with callbacks to generate the objects when needed.
743  *
744  * @param leaf The surface where the objects should be placed.
745  * @param branch The branch that will hold the randomly-placed objects.
746  * @param center The center of the leaf in FlightGear coordinates.
747  * @param lon_deg The longitude of the surface center, in degrees.
748  * @param lat_deg The latitude of the surface center, in degrees.
749  * @param material_name The name of the surface's material.
750  */
751 static void
752 gen_random_surface_objects (ssgLeaf *leaf,
753                             ssgBranch *branch,
754                             Point3D * center,
755                             const string &material_name)
756 {
757                                 // If the surface has no triangles, return
758                                 // now.
759     int num_tris = leaf->getNumTriangles();
760     if (num_tris < 1)
761       return;
762
763                                 // Get the material for this surface.
764     FGNewMat * mat = material_lib.find(material_name);
765     if (mat == 0) {
766       SG_LOG(SG_INPUT, SG_ALERT, "Unknown material " << material_name);
767       return;
768     }
769
770                                 // If the material has no randomly-placed
771                                 // objects, return now.
772     if (mat->get_object_group_count() < 1)
773       return;
774
775                                 // Calculate the geodetic centre of
776                                 // the tile, for aligning automatic
777                                 // objects.
778     double lon_deg, lat_rad, lat_deg, alt_m, sl_radius_m;
779     Point3D geoc = sgCartToPolar3d(*center);
780     lon_deg = geoc.lon() * SGD_RADIANS_TO_DEGREES;
781     sgGeocToGeod(geoc.lat(), geoc.radius(),
782                  &lat_rad, &alt_m, &sl_radius_m);
783     lat_deg = lat_rad * SGD_RADIANS_TO_DEGREES;
784
785                                 // LOD for the leaf
786                                 // max random object range: 20000m
787     float ranges[] = {0, 20000, 1000000};
788     ssgRangeSelector * lod = new ssgRangeSelector;
789     lod->setRanges(ranges, 3);
790     branch->addKid(lod);
791
792                                 // Create the in-range and out-of-range
793                                 // branches.
794     ssgBranch * in_range = new ssgBranch;
795     ssgBranch * out_of_range = new ssgBranch;
796     lod->addKid(in_range);
797     lod->addKid(out_of_range);
798
799     LeafUserData * data = new LeafUserData;
800     data->is_filled_in = false;
801     data->leaf = leaf;
802     data->mat = mat;
803     data->branch = in_range;
804     data->lon_deg = lon_deg;
805     data->lat_deg = lat_deg;
806
807     in_range->setUserData(data);
808     in_range->setTravCallback(SSG_CALLBACK_PRETRAV, leaf_in_range_callback);
809     out_of_range->setUserData(data);
810     out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
811                                    leaf_out_of_range_callback);
812     out_of_range
813       ->addKid(new DummyBSphereEntity(leaf->getBSphere()->getRadius()));
814 }
815
816
817 \f
818 ////////////////////////////////////////////////////////////////////////
819 // Scenery loaders.
820 ////////////////////////////////////////////////////////////////////////
821
822
823 // Load an Ascii obj file
824 ssgBranch *fgAsciiObjLoad( const string& path, FGTileEntry *t,
825                            ssgVertexArray *lights, const bool is_base)
826 {
827     FGNewMat *newmat = NULL;
828     string material;
829     float coverage = -1;
830     Point3D pp;
831     // sgVec3 approx_normal;
832     // double normal[3], scale = 0.0;
833     // double x, y, z, xmax, xmin, ymax, ymin, zmax, zmin;
834     // GLfloat sgenparams[] = { 1.0, 0.0, 0.0, 0.0 };
835     // GLint display_list = 0;
836     int shading;
837     bool in_faces = false;
838     int vncount, vtcount;
839     int n1 = 0, n2 = 0, n3 = 0;
840     int tex;
841     // int last1 = 0, last2 = 0;
842     bool odd = false;
843     point_list nodes;
844     Point3D node;
845     Point3D center;
846     double scenery_version = 0.0;
847     double tex_width = 1000.0, tex_height = 1000.0;
848     bool shared_done = false;
849     int_list fan_vertices;
850     int_list fan_tex_coords;
851     int i;
852     ssgSimpleState *state = NULL;
853     sgVec3 *vtlist, *vnlist;
854     sgVec2 *tclist;
855
856     ssgBranch *tile = new ssgBranch () ;
857
858     tile -> setName ( (char *)path.c_str() ) ;
859
860     // Attempt to open "path.gz" or "path"
861     sg_gzifstream in( path );
862     if ( ! in.is_open() ) {
863         SG_LOG( SG_TERRAIN, SG_DEBUG, "Cannot open file: " << path );
864         SG_LOG( SG_TERRAIN, SG_DEBUG, "default to ocean tile: " << path );
865
866         delete tile;
867
868         return NULL;
869     }
870
871     shading = fgGetBool("/sim/rendering/shading");
872
873     if ( is_base ) {
874         t->ncount = 0;
875     }
876     vncount = 0;
877     vtcount = 0;
878     if ( is_base ) {
879         t->bounding_radius = 0.0;
880     }
881     center = t->center;
882
883     // StopWatch stopwatch;
884     // stopwatch.start();
885
886     // ignore initial comments and blank lines. (priming the pump)
887     // in >> skipcomment;
888     // string line;
889
890     string token;
891     char c;
892
893 #ifdef __MWERKS__
894     while ( in.get(c) && c  != '\0' ) {
895         in.putback(c);
896 #else
897     while ( ! in.eof() ) {
898 #endif
899
900         in >> ::skipws;
901
902         if ( in.get( c ) && c == '#' ) {
903             // process a comment line
904
905             // getline( in, line );
906             // cout << "comment = " << line << endl;
907
908             in >> token;
909
910             if ( token == "Version" ) {
911                 // read scenery versions number
912                 in >> scenery_version;
913                 // cout << "scenery_version = " << scenery_version << endl;
914                 if ( scenery_version > 0.4 ) {
915                     SG_LOG( SG_TERRAIN, SG_ALERT, 
916                             "\nYou are attempting to load a tile format that\n"
917                             << "is newer than this version of flightgear can\n"
918                             << "handle.  You should upgrade your copy of\n"
919                             << "FlightGear to the newest version.  For\n"
920                             << "details, please see:\n"
921                             << "\n    http://www.flightgear.org\n" );
922                     exit(-1);
923                 }
924             } else if ( token == "gbs" ) {
925                 // reference point (center offset)
926                 if ( is_base ) {
927                     in >> t->center >> t->bounding_radius;
928                 } else {
929                     Point3D junk1;
930                     double junk2;
931                     in >> junk1 >> junk2;
932                 }
933                 center = t->center;
934                 // cout << "center = " << center 
935                 //      << " radius = " << t->bounding_radius << endl;
936             } else if ( token == "bs" ) {
937                 // reference point (center offset)
938                 // (skip past this)
939                 Point3D junk1;
940                 double junk2;
941                 in >> junk1 >> junk2;
942             } else if ( token == "usemtl" ) {
943                 // material property specification
944
945                 // if first usemtl with shared_done = false, then set
946                 // shared_done true and build the ssg shared lists
947                 if ( ! shared_done ) {
948                     // sanity check
949                     if ( (int)nodes.size() != vncount ) {
950                         SG_LOG( SG_TERRAIN, SG_ALERT, 
951                                 "Tile has mismatched nodes = " << nodes.size()
952                                 << " and normals = " << vncount << " : " 
953                                 << path );
954                         // exit(-1);
955                     }
956                     shared_done = true;
957
958                     vtlist = new sgVec3 [ nodes.size() ];
959                     t->vec3_ptrs.push_back( vtlist );
960                     vnlist = new sgVec3 [ vncount ];
961                     t->vec3_ptrs.push_back( vnlist );
962                     tclist = new sgVec2 [ vtcount ];
963                     t->vec2_ptrs.push_back( tclist );
964
965                     for ( i = 0; i < (int)nodes.size(); ++i ) {
966                         sgSetVec3( vtlist[i], 
967                                    nodes[i][0], nodes[i][1], nodes[i][2] );
968                     }
969                     for ( i = 0; i < vncount; ++i ) {
970                         sgSetVec3( vnlist[i], 
971                                    normals[i][0], 
972                                    normals[i][1],
973                                    normals[i][2] );
974                     }
975                     for ( i = 0; i < vtcount; ++i ) {
976                         sgSetVec2( tclist[i],
977                                    tex_coords[i][0],
978                                    tex_coords[i][1] );
979                     }
980                 }
981
982                 // display_list = xglGenLists(1);
983                 // xglNewList(display_list, GL_COMPILE);
984                 // printf("xglGenLists(); xglNewList();\n");
985                 in_faces = false;
986
987                 // scan the material line
988                 in >> material;
989                 
990                 // find this material in the properties list
991
992                 newmat = material_lib.find( material );
993                 if ( newmat == NULL ) {
994                     // see if this is an on the fly texture
995                     string file = path;
996                     int pos = file.rfind( "/" );
997                     file = file.substr( 0, pos );
998                     // cout << "current file = " << file << endl;
999                     file += "/";
1000                     file += material;
1001                     // cout << "current file = " << file << endl;
1002                     if ( ! material_lib.add_item( file ) ) {
1003                         SG_LOG( SG_TERRAIN, SG_ALERT, 
1004                                 "Ack! unknown usemtl name = " << material 
1005                                 << " in " << path );
1006                     } else {
1007                         // locate our newly created material
1008                         newmat = material_lib.find( material );
1009                         if ( newmat == NULL ) {
1010                             SG_LOG( SG_TERRAIN, SG_ALERT, 
1011                                     "Ack! bad on the fly materia create = "
1012                                     << material << " in " << path );
1013                         }
1014                     }
1015                 }
1016
1017                 if ( newmat != NULL ) {
1018                     // set the texture width and height values for this
1019                     // material
1020                     tex_width = newmat->get_xsize();
1021                     tex_height = newmat->get_ysize();
1022                     state = newmat->get_state();
1023                     coverage = newmat->get_light_coverage();
1024                     // cout << "(w) = " << tex_width << " (h) = "
1025                     //      << tex_width << endl;
1026                 } else {
1027                     coverage = -1;
1028                 }
1029             } else {
1030                 // unknown comment, just gobble the input until the
1031                 // end of line
1032
1033                 in >> skipeol;
1034             }
1035         } else {
1036             in.putback( c );
1037         
1038             in >> token;
1039
1040             // cout << "token = " << token << endl;
1041
1042             if ( token == "vn" ) {
1043                 // vertex normal
1044                 if ( vncount < FG_MAX_NODES ) {
1045                     in >> normals[vncount][0]
1046                        >> normals[vncount][1]
1047                        >> normals[vncount][2];
1048                     vncount++;
1049                 } else {
1050                     SG_LOG( SG_TERRAIN, SG_ALERT, 
1051                             "Read too many vertex normals in " << path 
1052                             << " ... dying :-(" );
1053                     exit(-1);
1054                 }
1055             } else if ( token == "vt" ) {
1056                 // vertex texture coordinate
1057                 if ( vtcount < FG_MAX_NODES*3 ) {
1058                     in >> tex_coords[vtcount][0]
1059                        >> tex_coords[vtcount][1];
1060                     vtcount++;
1061                 } else {
1062                     SG_LOG( SG_TERRAIN, SG_ALERT, 
1063                             "Read too many vertex texture coords in " << path
1064                             << " ... dying :-("
1065                             );
1066                     exit(-1);
1067                 }
1068             } else if ( token == "v" ) {
1069                 // node (vertex)
1070                 if ( t->ncount < FG_MAX_NODES ) {
1071                     /* in >> nodes[t->ncount][0]
1072                        >> nodes[t->ncount][1]
1073                        >> nodes[t->ncount][2]; */
1074                     in >> node;
1075                     nodes.push_back(node);
1076                     if ( is_base ) {
1077                         t->ncount++;
1078                     }
1079                 } else {
1080                     SG_LOG( SG_TERRAIN, SG_ALERT, 
1081                             "Read too many nodes in " << path 
1082                             << " ... dying :-(");
1083                     exit(-1);
1084                 }
1085             } else if ( (token == "tf") || (token == "ts") || (token == "f") ) {
1086                 // triangle fan, strip, or individual face
1087                 // SG_LOG( SG_TERRAIN, SG_INFO, "new fan or strip");
1088
1089                 fan_vertices.clear();
1090                 fan_tex_coords.clear();
1091                 odd = true;
1092
1093                 // xglBegin(GL_TRIANGLE_FAN);
1094
1095                 in >> n1;
1096                 fan_vertices.push_back( n1 );
1097                 // xglNormal3dv(normals[n1]);
1098                 if ( in.get( c ) && c == '/' ) {
1099                     in >> tex;
1100                     fan_tex_coords.push_back( tex );
1101                     if ( scenery_version >= 0.4 ) {
1102                         if ( tex_width > 0 ) {
1103                             tclist[tex][0] *= (1000.0 / tex_width);
1104                         }
1105                         if ( tex_height > 0 ) {
1106                             tclist[tex][1] *= (1000.0 / tex_height);
1107                         }
1108                     }
1109                     pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1110                     pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1111                 } else {
1112                     in.putback( c );
1113                     pp = local_calc_tex_coords(nodes[n1], center);
1114                 }
1115                 // xglTexCoord2f(pp.x(), pp.y());
1116                 // xglVertex3dv(nodes[n1].get_n());
1117
1118                 in >> n2;
1119                 fan_vertices.push_back( n2 );
1120                 // xglNormal3dv(normals[n2]);
1121                 if ( in.get( c ) && c == '/' ) {
1122                     in >> tex;
1123                     fan_tex_coords.push_back( tex );
1124                     if ( scenery_version >= 0.4 ) {
1125                         if ( tex_width > 0 ) {
1126                             tclist[tex][0] *= (1000.0 / tex_width);
1127                         }
1128                         if ( tex_height > 0 ) {
1129                             tclist[tex][1] *= (1000.0 / tex_height);
1130                         }
1131                     }
1132                     pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1133                     pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1134                 } else {
1135                     in.putback( c );
1136                     pp = local_calc_tex_coords(nodes[n2], center);
1137                 }
1138                 // xglTexCoord2f(pp.x(), pp.y());
1139                 // xglVertex3dv(nodes[n2].get_n());
1140                 
1141                 // read all subsequent numbers until next thing isn't a number
1142                 while ( true ) {
1143                     in >> ::skipws;
1144
1145                     char c;
1146                     in.get(c);
1147                     in.putback(c);
1148                     if ( ! isdigit(c) || in.eof() ) {
1149                         break;
1150                     }
1151
1152                     in >> n3;
1153                     fan_vertices.push_back( n3 );
1154                     // cout << "  triangle = "
1155                     //      << n1 << "," << n2 << "," << n3
1156                     //      << endl;
1157                     // xglNormal3dv(normals[n3]);
1158                     if ( in.get( c ) && c == '/' ) {
1159                         in >> tex;
1160                         fan_tex_coords.push_back( tex );
1161                         if ( scenery_version >= 0.4 ) {
1162                             if ( tex_width > 0 ) {
1163                                 tclist[tex][0] *= (1000.0 / tex_width);
1164                             }
1165                             if ( tex_height > 0 ) {
1166                                 tclist[tex][1] *= (1000.0 / tex_height);
1167                             }
1168                         }
1169                         pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1170                         pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1171                     } else {
1172                         in.putback( c );
1173                         pp = local_calc_tex_coords(nodes[n3], center);
1174                     }
1175                     // xglTexCoord2f(pp.x(), pp.y());
1176                     // xglVertex3dv(nodes[n3].get_n());
1177
1178                     if ( (token == "tf") || (token == "f") ) {
1179                         // triangle fan
1180                         n2 = n3;
1181                     } else {
1182                         // triangle strip
1183                         odd = !odd;
1184                         n1 = n2;
1185                         n2 = n3;
1186                     }
1187                 }
1188
1189                 // xglEnd();
1190
1191                 // build the ssg entity
1192                 int size = (int)fan_vertices.size();
1193                 ssgVertexArray   *vl = new ssgVertexArray( size );
1194                 ssgNormalArray   *nl = new ssgNormalArray( size );
1195                 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1196                 ssgColourArray   *cl = new ssgColourArray( 1 );
1197
1198                 sgVec4 color;
1199                 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
1200                 cl->add( color );
1201
1202                 sgVec2 tmp2;
1203                 sgVec3 tmp3;
1204                 for ( i = 0; i < size; ++i ) {
1205                     sgCopyVec3( tmp3, vtlist[ fan_vertices[i] ] );
1206                     vl -> add( tmp3 );
1207
1208                     sgCopyVec3( tmp3, vnlist[ fan_vertices[i] ] );
1209                     nl -> add( tmp3 );
1210
1211                     sgCopyVec2( tmp2, tclist[ fan_tex_coords[i] ] );
1212                     tl -> add( tmp2 );
1213                 }
1214
1215                 ssgLeaf *leaf = NULL;
1216                 if ( token == "tf" ) {
1217                     // triangle fan
1218                     leaf = 
1219                         new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
1220                 } else if ( token == "ts" ) {
1221                     // triangle strip
1222                     leaf = 
1223                         new ssgVtxTable ( GL_TRIANGLE_STRIP, vl, nl, tl, cl );
1224                 } else if ( token == "f" ) {
1225                     // triangle
1226                     leaf = 
1227                         new ssgVtxTable ( GL_TRIANGLES, vl, nl, tl, cl );
1228                 }
1229                 // leaf->makeDList();
1230                 leaf->setState( state );
1231
1232                 tile->addKid( leaf );
1233
1234                 if ( is_base ) {
1235                     if ( coverage > 0.0 ) {
1236                         if ( coverage < 10000.0 ) {
1237                             SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1238                                    << coverage << ", pushing up to 10000");
1239                             coverage = 10000;
1240                         }
1241                         gen_random_surface_points(leaf, lights, coverage);
1242                     }
1243                 }
1244             } else {
1245                 SG_LOG( SG_TERRAIN, SG_WARN, "Unknown token in " 
1246                         << path << " = " << token );
1247             }
1248
1249             // eat white space before start of while loop so if we are
1250             // done with useful input it is noticed before hand.
1251             in >> ::skipws;
1252         }
1253     }
1254
1255     if ( is_base ) {
1256         t->nodes = nodes;
1257     }
1258
1259     // stopwatch.stop();
1260     // SG_LOG( SG_TERRAIN, SG_DEBUG, 
1261     //     "Loaded " << path << " in " 
1262     //     << stopwatch.elapsedSeconds() << " seconds" );
1263
1264     return tile;
1265 }
1266
1267
1268 ssgLeaf *gen_leaf( const string& path,
1269                    const GLenum ty, const string& material,
1270                    const point_list& nodes, const point_list& normals,
1271                    const point_list& texcoords,
1272                    const int_list node_index,
1273                    const int_list normal_index,
1274                    const int_list& tex_index,
1275                    const bool calc_lights, ssgVertexArray *lights )
1276 {
1277     double tex_width = 1000.0, tex_height = 1000.0;
1278     ssgSimpleState *state = NULL;
1279     float coverage = -1;
1280
1281     FGNewMat *newmat = material_lib.find( material );
1282     if ( newmat == NULL ) {
1283         // see if this is an on the fly texture
1284         string file = path;
1285         int pos = file.rfind( "/" );
1286         file = file.substr( 0, pos );
1287         // cout << "current file = " << file << endl;
1288         file += "/";
1289         file += material;
1290         // cout << "current file = " << file << endl;
1291         if ( ! material_lib.add_item( file ) ) {
1292             SG_LOG( SG_TERRAIN, SG_ALERT, 
1293                     "Ack! unknown usemtl name = " << material 
1294                     << " in " << path );
1295         } else {
1296             // locate our newly created material
1297             newmat = material_lib.find( material );
1298             if ( newmat == NULL ) {
1299                 SG_LOG( SG_TERRAIN, SG_ALERT, 
1300                         "Ack! bad on the fly material create = "
1301                         << material << " in " << path );
1302             }
1303         }
1304     }
1305
1306     if ( newmat != NULL ) {
1307         // set the texture width and height values for this
1308         // material
1309         tex_width = newmat->get_xsize();
1310         tex_height = newmat->get_ysize();
1311         state = newmat->get_state();
1312         coverage = newmat->get_light_coverage();
1313         // cout << "(w) = " << tex_width << " (h) = "
1314         //      << tex_width << endl;
1315     } else {
1316         coverage = -1;
1317     }
1318
1319     sgVec2 tmp2;
1320     sgVec3 tmp3;
1321     sgVec4 tmp4;
1322     int i;
1323
1324     // vertices
1325     int size = node_index.size();
1326     if ( size < 1 ) {
1327         SG_LOG( SG_TERRAIN, SG_ALERT, "Woh! node list size < 1" );
1328         exit(-1);
1329     }
1330     ssgVertexArray *vl = new ssgVertexArray( size );
1331     Point3D node;
1332     for ( i = 0; i < size; ++i ) {
1333         node = nodes[ node_index[i] ];
1334         sgSetVec3( tmp3, node[0], node[1], node[2] );
1335         vl -> add( tmp3 );
1336     }
1337
1338     // normals
1339     Point3D normal;
1340     ssgNormalArray *nl = new ssgNormalArray( size );
1341     if ( normal_index.size() ) {
1342         // object file specifies normal indices (i.e. normal indices
1343         // aren't 'implied'
1344         for ( i = 0; i < size; ++i ) {
1345             normal = normals[ normal_index[i] ];
1346             sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1347             nl -> add( tmp3 );
1348         }
1349     } else {
1350         // use implied normal indices.  normal index = vertex index.
1351         for ( i = 0; i < size; ++i ) {
1352             normal = normals[ node_index[i] ];
1353             sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1354             nl -> add( tmp3 );
1355         }
1356     }
1357
1358     // colors
1359     ssgColourArray *cl = new ssgColourArray( 1 );
1360     sgSetVec4( tmp4, 1.0, 1.0, 1.0, 1.0 );
1361     cl->add( tmp4 );
1362
1363     // texture coordinates
1364     size = tex_index.size();
1365     Point3D texcoord;
1366     ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1367     if ( size == 1 ) {
1368         texcoord = texcoords[ tex_index[0] ];
1369         sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1370         sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1371         if ( tex_width > 0 ) {
1372             tmp2[0] *= (1000.0 / tex_width);
1373         }
1374         if ( tex_height > 0 ) {
1375             tmp2[1] *= (1000.0 / tex_height);
1376         }
1377         tl -> add( tmp2 );
1378     } else if ( size > 1 ) {
1379         for ( i = 0; i < size; ++i ) {
1380             texcoord = texcoords[ tex_index[i] ];
1381             sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1382             if ( tex_width > 0 ) {
1383                 tmp2[0] *= (1000.0 / tex_width);
1384             }
1385             if ( tex_height > 0 ) {
1386                 tmp2[1] *= (1000.0 / tex_height);
1387             }
1388             tl -> add( tmp2 );
1389         }
1390     }
1391
1392     ssgLeaf *leaf = new ssgVtxTable ( ty, vl, nl, tl, cl );
1393
1394     // lookup the state record
1395
1396     leaf->setState( state );
1397
1398     if ( calc_lights ) {
1399         if ( coverage > 0.0 ) {
1400             if ( coverage < 10000.0 ) {
1401                 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1402                        << coverage << ", pushing up to 10000");
1403                 coverage = 10000;
1404             }
1405             gen_random_surface_points(leaf, lights, coverage);
1406         }
1407     }
1408
1409     return leaf;
1410 }
1411
1412
1413 // Load an Binary obj file
1414 bool fgBinObjLoad( const string& path, const bool is_base,
1415                    Point3D *center,
1416                    double *bounding_radius,
1417                    ssgBranch* geometry,
1418                    ssgBranch* rwy_lights,
1419                    ssgVertexArray *ground_lights )
1420 {
1421     SGBinObject obj;
1422     bool use_random_objects =
1423       fgGetBool("/sim/rendering/random-objects", true);
1424
1425     if ( ! obj.read_bin( path ) ) {
1426         return false;
1427     }
1428
1429     geometry->setName( (char *)path.c_str() );
1430
1431     if ( is_base ) {
1432         // reference point (center offset/bounding sphere)
1433         *center = obj.get_gbs_center();
1434         *bounding_radius = obj.get_gbs_radius();
1435
1436     }
1437
1438     point_list nodes = obj.get_wgs84_nodes();
1439     point_list colors = obj.get_colors();
1440     point_list normals = obj.get_normals();
1441     point_list texcoords = obj.get_texcoords();
1442
1443     string material, tmp_mat;
1444     int_list vertex_index;
1445     int_list normal_index;
1446     int_list tex_index;
1447
1448     int i;
1449     bool is_lighting = false;
1450
1451     // generate points
1452     string_list pt_materials = obj.get_pt_materials();
1453     group_list pts_v = obj.get_pts_v();
1454     group_list pts_n = obj.get_pts_n();
1455     for ( i = 0; i < (int)pts_v.size(); ++i ) {
1456         // cout << "pts_v.size() = " << pts_v.size() << endl;
1457         tmp_mat = pt_materials[i];
1458         if ( tmp_mat.substr(0, 3) == "RWY" ) {
1459             material = "LIGHTS";
1460             is_lighting = true;
1461         } else {
1462             material = tmp_mat;
1463         }
1464         vertex_index = pts_v[i];
1465         normal_index = pts_n[i];
1466         tex_index.clear();
1467         ssgLeaf *leaf = gen_leaf( path, GL_POINTS, material,
1468                                   nodes, normals, texcoords,
1469                                   vertex_index, normal_index, tex_index,
1470                                   false, ground_lights );
1471
1472         if ( is_lighting ) {
1473             float ranges[] = { 0, 12000 };
1474             leaf->setCallback(SSG_CALLBACK_PREDRAW, runway_lights_predraw);
1475             ssgRangeSelector * lod = new ssgRangeSelector;
1476             lod->setRanges(ranges, 2);
1477             lod->addKid(leaf);
1478             rwy_lights->addKid(lod);
1479         } else {
1480             geometry->addKid( leaf );
1481         }
1482     }
1483
1484     // Put all randomly-placed objects under a separate branch
1485     // (actually an ssgRangeSelector) named "random-models".
1486     ssgBranch * random_object_branch = 0;
1487     if (use_random_objects) {
1488       float ranges[] = {0, 20000}; // Maximum 20km range for random objects
1489       ssgRangeSelector * object_lod = new ssgRangeSelector;
1490       object_lod->setRanges(ranges, 2);
1491       object_lod->setName("random-models");
1492       geometry->addKid(object_lod);
1493       random_object_branch = new ssgBranch;
1494       object_lod->addKid(random_object_branch);
1495     }
1496
1497     // generate triangles
1498     string_list tri_materials = obj.get_tri_materials();
1499     group_list tris_v = obj.get_tris_v();
1500     group_list tris_n = obj.get_tris_n();
1501     group_list tris_tc = obj.get_tris_tc();
1502     for ( i = 0; i < (int)tris_v.size(); ++i ) {
1503         material = tri_materials[i];
1504         vertex_index = tris_v[i];
1505         normal_index = tris_n[i];
1506         tex_index = tris_tc[i];
1507         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLES, material,
1508                                   nodes, normals, texcoords,
1509                                   vertex_index, normal_index, tex_index,
1510                                   is_base, ground_lights );
1511
1512         if (use_random_objects)
1513           gen_random_surface_objects(leaf, random_object_branch,
1514                                      center, material);
1515         geometry->addKid( leaf );
1516     }
1517
1518     // generate strips
1519     string_list strip_materials = obj.get_strip_materials();
1520     group_list strips_v = obj.get_strips_v();
1521     group_list strips_n = obj.get_strips_n();
1522     group_list strips_tc = obj.get_strips_tc();
1523     for ( i = 0; i < (int)strips_v.size(); ++i ) {
1524         material = strip_materials[i];
1525         vertex_index = strips_v[i];
1526         normal_index = strips_n[i];
1527         tex_index = strips_tc[i];
1528         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_STRIP, material,
1529                                   nodes, normals, texcoords,
1530                                   vertex_index, normal_index, tex_index,
1531                                   is_base, ground_lights );
1532
1533         if (use_random_objects)
1534           gen_random_surface_objects(leaf, random_object_branch,
1535                                      center, material);
1536         geometry->addKid( leaf );
1537     }
1538
1539     // generate fans
1540     string_list fan_materials = obj.get_fan_materials();
1541     group_list fans_v = obj.get_fans_v();
1542     group_list fans_n = obj.get_fans_n();
1543     group_list fans_tc = obj.get_fans_tc();
1544     for ( i = 0; i < (int)fans_v.size(); ++i ) {
1545         material = fan_materials[i];
1546         vertex_index = fans_v[i];
1547         normal_index = fans_n[i];
1548         tex_index = fans_tc[i];
1549         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_FAN, material,
1550                                   nodes, normals, texcoords,
1551                                   vertex_index, normal_index, tex_index,
1552                                   is_base, ground_lights );
1553         if (use_random_objects)
1554           gen_random_surface_objects(leaf, random_object_branch,
1555                                      center, material);
1556         geometry->addKid( leaf );
1557     }
1558
1559     return true;
1560 }