]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tileentry.cxx
Enable two sided lighting calculations when specular highlight is enabled
[flightgear.git] / src / Scenery / tileentry.cxx
1 // tileentry.cxx -- routines to handle a scenery tile
2 //
3 // Written by Curtis Olson, started May 1998.
4 //
5 // Copyright (C) 1998 - 2001  Curtis L. Olson  - curt@flightgear.org
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 #include <simgear/compiler.h>
29
30 #include <Main/main.hxx>
31
32
33 #include STL_STRING
34
35 #include <simgear/bucket/newbucket.hxx>
36 #include <simgear/debug/logstream.hxx>
37 #include <simgear/math/sg_geodesy.hxx>
38 #include <simgear/math/sg_random.h>
39 #include <simgear/misc/sgstream.hxx>
40 #include <simgear/scene/material/mat.hxx>
41 #include <simgear/scene/material/matlib.hxx>
42 #include <simgear/scene/tgdb/apt_signs.hxx>
43 #include <simgear/scene/tgdb/obj.hxx>
44
45 #include <Aircraft/aircraft.hxx>
46 #include <Include/general.hxx>
47 #include <Main/fg_props.hxx>
48 #include <Main/globals.hxx>
49 #include <Main/viewer.hxx>
50 #include <Scenery/scenery.hxx>
51 #include <Time/light.hxx>
52
53 #include "tileentry.hxx"
54 #include "tilemgr.hxx"
55
56 SG_USING_STD(string);
57
58
59 // Constructor
60 FGTileEntry::FGTileEntry ( const SGBucket& b )
61     : center( Point3D( 0.0 ) ),
62       tile_bucket( b ),
63       terra_transform( new ssgTransform ),
64       rwy_lights_transform( new ssgTransform ),
65       taxi_lights_transform( new ssgTransform ),
66       terra_range( new ssgRangeSelector ),
67       rwy_lights_selector( new ssgSelector ),
68       taxi_lights_selector( new ssgSelector ),
69       loaded(false),
70       pending_models(0),
71       free_tracker(0)
72 {
73     // update the contents
74     // if ( vec3_ptrs.size() || vec2_ptrs.size() || index_ptrs.size() ) {
75     //     SG_LOG( SG_TERRAIN, SG_ALERT, 
76     //             "Attempting to overwrite existing or"
77     //             << " not properly freed leaf data." );
78     //     exit(-1);
79     // }
80 }
81
82
83 // Destructor
84 FGTileEntry::~FGTileEntry () {
85     // cout << "nodes = " << nodes.size() << endl;;
86     // delete[] nodes;
87 }
88
89
90 #if 0
91 // Please keep this for reference.  We use Norman's optimized routine,
92 // but here is what the routine really is doing.
93 void
94 FGTileEntry::WorldCoordinate( sgCoord *obj_pos, Point3D center,
95                               double lat, double lon, double elev, double hdg)
96 {
97     // setup transforms
98     Point3D geod( lon * SGD_DEGREES_TO_RADIANS,
99                   lat * SGD_DEGREES_TO_RADIANS,
100                   elev );
101         
102     Point3D world_pos = sgGeodToCart( geod );
103     Point3D offset = world_pos - center;
104         
105     sgMat4 POS;
106     sgMakeTransMat4( POS, offset.x(), offset.y(), offset.z() );
107
108     sgVec3 obj_rt, obj_up;
109     sgSetVec3( obj_rt, 0.0, 1.0, 0.0); // Y axis
110     sgSetVec3( obj_up, 0.0, 0.0, 1.0); // Z axis
111
112     sgMat4 ROT_lon, ROT_lat, ROT_hdg;
113     sgMakeRotMat4( ROT_lon, lon, obj_up );
114     sgMakeRotMat4( ROT_lat, 90 - lat, obj_rt );
115     sgMakeRotMat4( ROT_hdg, hdg, obj_up );
116
117     sgMat4 TUX;
118     sgCopyMat4( TUX, ROT_hdg );
119     sgPostMultMat4( TUX, ROT_lat );
120     sgPostMultMat4( TUX, ROT_lon );
121     sgPostMultMat4( TUX, POS );
122
123     sgSetCoord( obj_pos, TUX );
124 }
125 #endif
126
127
128 // Norman's 'fast hack' for above
129 static void WorldCoordinate( sgCoord *obj_pos, Point3D center, double lat,
130                              double lon, double elev, double hdg )
131 {
132     double lon_rad = lon * SGD_DEGREES_TO_RADIANS;
133     double lat_rad = lat * SGD_DEGREES_TO_RADIANS;
134     double hdg_rad = hdg * SGD_DEGREES_TO_RADIANS;
135
136     // setup transforms
137     Point3D geod( lon_rad, lat_rad, elev );
138         
139     Point3D world_pos = sgGeodToCart( geod );
140     Point3D offset = world_pos - center;
141
142     sgMat4 mat;
143
144     SGfloat sin_lat = (SGfloat)sin( lat_rad );
145     SGfloat cos_lat = (SGfloat)cos( lat_rad );
146     SGfloat cos_lon = (SGfloat)cos( lon_rad );
147     SGfloat sin_lon = (SGfloat)sin( lon_rad );
148     SGfloat sin_hdg = (SGfloat)sin( hdg_rad ) ;
149     SGfloat cos_hdg = (SGfloat)cos( hdg_rad ) ;
150
151     mat[0][0] =  cos_hdg * (SGfloat)sin_lat * (SGfloat)cos_lon - sin_hdg * (SGfloat)sin_lon;
152     mat[0][1] =  cos_hdg * (SGfloat)sin_lat * (SGfloat)sin_lon + sin_hdg * (SGfloat)cos_lon;
153     mat[0][2] = -cos_hdg * (SGfloat)cos_lat;
154     mat[0][3] =  SG_ZERO;
155
156     mat[1][0] = -sin_hdg * (SGfloat)sin_lat * (SGfloat)cos_lon - cos_hdg * (SGfloat)sin_lon;
157     mat[1][1] = -sin_hdg * (SGfloat)sin_lat * (SGfloat)sin_lon + cos_hdg * (SGfloat)cos_lon;
158     mat[1][2] =  sin_hdg * (SGfloat)cos_lat;
159     mat[1][3] =  SG_ZERO;
160
161     mat[2][0] = (SGfloat)cos_lat * (SGfloat)cos_lon;
162     mat[2][1] = (SGfloat)cos_lat * (SGfloat)sin_lon;
163     mat[2][2] = (SGfloat)sin_lat;
164     mat[2][3] =  SG_ZERO;
165
166     mat[3][0] = offset.x();
167     mat[3][1] = offset.y();
168     mat[3][2] = offset.z();
169     mat[3][3] = SG_ONE ;
170
171     sgSetCoord( obj_pos, mat );
172 }
173
174
175 // recurse an ssg tree and call removeKid() on every node from the
176 // bottom up.  Leaves the original branch in existance, but empty so
177 // it can be removed by the calling routine.
178 static void my_remove_branch( ssgBranch * branch ) {
179     for ( ssgEntity *k = branch->getKid( 0 );
180           k != NULL; 
181           k = branch->getNextKid() )
182     {
183         if ( k -> isAKindOf ( ssgTypeBranch() ) ) {
184             my_remove_branch( (ssgBranch *)k );
185             branch -> removeKid ( k );
186         } else if ( k -> isAKindOf ( ssgTypeLeaf() ) ) {
187             branch -> removeKid ( k ) ;
188         }
189     }
190 }
191
192
193 // Free "n" leaf elements of an ssg tree.  returns the number of
194 // elements freed.  An empty branch node is considered a leaf.  This
195 // is intended to spread the load of freeing a complex tile out over
196 // several frames.
197 static int fgPartialFreeSSGtree( ssgBranch *b, int n ) {
198
199 #if 0
200     // for testing: we could call the following two lines and replace
201     // the functionality of this entire function and everything will
202     // get properly freed, but it will happen all at once and could
203     // cause a huge frame rate hit.
204     ssgDeRefDelete( b );
205     return 0;
206 #endif
207
208     int num_deletes = 0;
209
210     if ( n > 0 ) {
211         // we still have some delete budget left
212         // if ( b->getNumKids() > 100 ) {
213         //     cout << "large family = " << b->getNumKids() << endl;
214         // }
215         // deleting in reverse would help if my plib patch get's
216         // applied, but for now it will make things slower.
217         // for ( int i = b->getNumKids() - 1; i >= 0 ; --i ) {
218         for ( int i = 0; i < b->getNumKids(); ++i ) {
219             ssgEntity *kid = b->getKid(i);
220             if ( kid->isAKindOf( ssgTypeBranch() ) && kid->getRef() <= 1 ) {
221                 int result = fgPartialFreeSSGtree( (ssgBranch *)kid, n );
222                 num_deletes += result;
223                 n -= result;
224                 if ( n < 0 ) {
225                     break;
226                 }
227             }
228             // remove the kid if (a) it is now empty -or- (b) it's ref
229             // count is > zero at which point we don't care if it's
230             // empty, we don't want to touch it's contents.
231             if ( kid->getNumKids() == 0 || kid->getRef() > 1 ) {
232                 b->removeKid( kid );
233                 num_deletes++;
234                 n--;
235             }
236         }
237     }
238
239     return num_deletes;
240 }
241
242
243 // Clean up the memory used by this tile and delete the arrays used by
244 // ssg as well as the whole ssg branch
245 bool FGTileEntry::free_tile() {
246     int delete_size = 100;
247     SG_LOG( SG_TERRAIN, SG_DEBUG,
248             "FREEING TILE = (" << tile_bucket << ")" );
249
250     SG_LOG( SG_TERRAIN, SG_DEBUG, "(start) free_tracker = " << free_tracker );
251     
252     if ( !(free_tracker & NODES) ) {
253         free_tracker |= NODES;
254     } else if ( !(free_tracker & VEC_PTRS) ) {
255         free_tracker |= VEC_PTRS;
256     } else if ( !(free_tracker & TERRA_NODE) ) {
257         // delete the terrain branch (this should already have been
258         // disconnected from the scene graph)
259         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING terra_transform" );
260         if ( fgPartialFreeSSGtree( terra_transform, delete_size ) == 0 ) {
261             ssgDeRefDelete( terra_transform );
262             free_tracker |= TERRA_NODE;
263         }
264     } else if ( !(free_tracker & GROUND_LIGHTS) && gnd_lights_transform ) {
265         // delete the terrain lighting branch (this should already have been
266         // disconnected from the scene graph)
267         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING gnd_lights_transform" );
268         if ( fgPartialFreeSSGtree( gnd_lights_transform, delete_size ) == 0 ) {
269             ssgDeRefDelete( gnd_lights_transform );
270             free_tracker |= GROUND_LIGHTS;
271         }
272     } else if ( !(free_tracker & RWY_LIGHTS) && rwy_lights_selector ) {
273         // delete the runway lighting branch (this should already have
274         // been disconnected from the scene graph)
275         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING rwy_lights_selector" );
276         if ( fgPartialFreeSSGtree( rwy_lights_selector, delete_size ) == 0 ) {
277             ssgDeRefDelete( rwy_lights_selector );
278             free_tracker |= RWY_LIGHTS;
279         }
280     } else if ( !(free_tracker & TAXI_LIGHTS) && taxi_lights_selector ) {
281         // delete the taxi lighting branch (this should already have been
282         // disconnected from the scene graph)
283         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING taxi_lights_selector" );
284         if ( fgPartialFreeSSGtree( taxi_lights_selector, delete_size ) == 0 ) {
285             ssgDeRefDelete( taxi_lights_selector );
286             free_tracker |= TAXI_LIGHTS;
287         }
288     } else if ( !(free_tracker & LIGHTMAPS) ) {
289         free_tracker |= LIGHTMAPS;
290     } else {
291         return true;
292     }
293
294     SG_LOG( SG_TERRAIN, SG_DEBUG, "(end) free_tracker = " << free_tracker );
295
296     // if we fall down to here, we still have work todo, return false
297     return false;
298 }
299
300
301 // Update the ssg transform node for this tile so it can be
302 // properly drawn relative to our (0,0,0) point
303 void FGTileEntry::prep_ssg_node( const Point3D& p, sgVec3 up, float vis) {
304     if ( !loaded ) return;
305
306     SetOffset( p );
307
308     // visibility can change from frame to frame so we update the
309     // range selector cutoff's each time.
310     terra_range->setRange( 0, SG_ZERO );
311     terra_range->setRange( 1, vis + bounding_radius );
312
313     if ( gnd_lights_range ) {
314         gnd_lights_range->setRange( 0, SG_ZERO );
315         gnd_lights_range->setRange( 1, vis * 1.5 + bounding_radius );
316     }
317
318     sgVec3 sgTrans;
319     sgSetVec3( sgTrans, offset.x(), offset.y(), offset.z() );
320     terra_transform->setTransform( sgTrans );
321
322     if ( gnd_lights_transform ) {
323         // we need to lift the lights above the terrain to avoid
324         // z-buffer fighting.  We do this based on our altitude and
325         // the distance this tile is away from scenery center.
326
327         // we expect 'up' to be a unit vector coming in, but since we
328         // modify the value of lift_vec, we need to create a local
329         // copy.
330         sgVec3 lift_vec;
331         sgCopyVec3( lift_vec, up );
332
333         double agl;
334         agl = globals->get_current_view()->getAltitudeASL_ft()
335             * SG_FEET_TO_METER - globals->get_scenery()->get_cur_elev();
336
337         // sgTrans just happens to be the
338         // vector from scenery center to the center of this tile which
339         // is what we want to calculate the distance of
340         sgVec3 to;
341         sgCopyVec3( to, sgTrans );
342         double dist = sgLengthVec3( to );
343
344         if ( general.get_glDepthBits() > 16 ) {
345             sgScaleVec3( lift_vec, 10.0 + agl / 100.0 + dist / 10000 );
346         } else {
347             sgScaleVec3( lift_vec, 10.0 + agl / 20.0 + dist / 5000 );
348         }
349
350         sgVec3 lt_trans;
351         sgCopyVec3( lt_trans, sgTrans );
352
353         sgAddVec3( lt_trans, lift_vec );
354         gnd_lights_transform->setTransform( lt_trans );
355
356         // select which set of lights based on sun angle
357         float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
358         if ( sun_angle > 95 ) {
359             gnd_lights_brightness->select(0x04);
360         } else if ( sun_angle > 92 ) {
361             gnd_lights_brightness->select(0x02);
362         } else if ( sun_angle > 89 ) {
363             gnd_lights_brightness->select(0x01);
364         } else {
365             gnd_lights_brightness->select(0x00);
366         }
367     }
368
369     if ( rwy_lights_transform ) {
370         // we need to lift the lights above the terrain to avoid
371         // z-buffer fighting.  We do this based on our altitude and
372         // the distance this tile is away from scenery center.
373
374         sgVec3 lift_vec;
375         sgCopyVec3( lift_vec, up );
376
377         // we fudge agl by 30 meters so that the lifting function
378         // doesn't phase in until we are > 30m agl.
379         double agl;
380         agl = globals->get_current_view()->getAltitudeASL_ft()
381             * SG_FEET_TO_METER - globals->get_scenery()->get_cur_elev()
382             - 30.0;
383         if ( agl < 0.0 ) {
384             agl = 0.0;
385         }
386         
387         if ( general.get_glDepthBits() > 16 ) {
388             sgScaleVec3( lift_vec, 0.0 + agl / 500.0 );
389         } else {
390             sgScaleVec3( lift_vec, 0.0 + agl / 150.0 );
391         }
392
393         sgVec3 lt_trans;
394         sgCopyVec3( lt_trans, sgTrans );
395
396         sgAddVec3( lt_trans, lift_vec );
397         rwy_lights_transform->setTransform( lt_trans );
398
399         // turn runway lights on/off based on sun angle and visibility
400         float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
401         if ( sun_angle > 85 ||
402              (fgGetDouble("/environment/visibility-m") < 5000.0) ) {
403             rwy_lights_selector->select(0x01);
404         } else {
405             rwy_lights_selector->select(0x00);
406         }
407     }
408
409     if ( taxi_lights_transform ) {
410         // we need to lift the lights above the terrain to avoid
411         // z-buffer fighting.  We do this based on our altitude and
412         // the distance this tile is away from scenery center.
413
414         sgVec3 lift_vec;
415         sgCopyVec3( lift_vec, up );
416
417         // we fudge agl by 30 meters so that the lifting function
418         // doesn't phase in until we are > 30m agl.
419         double agl;
420         agl = globals->get_current_view()->getAltitudeASL_ft()
421             * SG_FEET_TO_METER - globals->get_scenery()->get_cur_elev()
422             - 30.0;
423         if ( agl < 0.0 ) {
424             agl = 0.0;
425         }
426         
427         if ( general.get_glDepthBits() > 16 ) {
428             sgScaleVec3( lift_vec, 0.0 + agl / 500.0 );
429         } else {
430             sgScaleVec3( lift_vec, 0.0 + agl / 150.0 );
431         }
432
433         sgVec3 lt_trans;
434         sgCopyVec3( lt_trans, sgTrans );
435
436         sgAddVec3( lt_trans, lift_vec );
437         taxi_lights_transform->setTransform( lt_trans );
438
439         // turn taxi lights on/off based on sun angle and visibility
440         float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
441         if ( sun_angle > 85 ||
442              (fgGetDouble("/environment/visibility-m") < 5000.0) ) {
443             taxi_lights_selector->select(0x01);
444         } else {
445             taxi_lights_selector->select(0x00);
446         }
447     }
448 }
449
450
451 // Set up lights rendering call backs
452 static int fgLightsPredraw( ssgEntity *e ) {
453 #if 0
454     if (glPointParameterIsSupported) {
455         static float quadratic[3] = {1.0, 0.01, 0.0001};
456         glPointParameterfvProc(GL_DISTANCE_ATTENUATION_EXT, quadratic);
457         glPointParameterfProc(GL_POINT_SIZE_MIN_EXT, 1.0); 
458         glPointSize(4.0);
459     }
460 #endif
461     return true;
462 }
463
464 static int fgLightsPostdraw( ssgEntity *e ) {
465 #if 0
466     if (glPointParameterIsSupported) {
467         static float default_attenuation[3] = {1.0, 0.0, 0.0};
468         glPointParameterfvProc(GL_DISTANCE_ATTENUATION_EXT,
469                               default_attenuation);
470         glPointSize(1.0);
471     }
472 #endif
473     return true;
474 }
475
476
477 ssgLeaf* FGTileEntry::gen_lights( SGMaterialLib *matlib, ssgVertexArray *lights,
478                                   int inc, float bright )
479 {
480     // generate a repeatable random seed
481     float *p1 = lights->get( 0 );
482     unsigned int *seed = (unsigned int *)p1;
483     sg_srandom( *seed );
484
485     int size = lights->getNum() / inc;
486
487     // Allocate ssg structure
488     ssgVertexArray   *vl = new ssgVertexArray( size + 1 );
489     ssgNormalArray   *nl = NULL;
490     ssgTexCoordArray *tl = NULL;
491     ssgColourArray   *cl = new ssgColourArray( size + 1 );
492
493     sgVec4 color;
494     for ( int i = 0; i < lights->getNum(); ++i ) {
495         // this loop is slightly less efficient than it otherwise
496         // could be, but we want a red light to always be red, and a
497         // yellow light to always be yellow, etc. so we are trying to
498         // preserve the random sequence.
499         float zombie = sg_random();
500         if ( i % inc == 0 ) {
501             vl->add( lights->get(i) );
502
503             // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
504             float factor = sg_random();
505             factor *= factor;
506
507             if ( zombie > 0.5 ) {
508                 // 50% chance of yellowish
509                 sgSetVec4( color, 0.9, 0.9, 0.3, bright - factor * 0.2 );
510             } else if ( zombie > 0.15 ) {
511                 // 35% chance of whitish
512                 sgSetVec4( color, 0.9, 0.9, 0.8, bright - factor * 0.2 );
513             } else if ( zombie > 0.05 ) {
514                 // 10% chance of orangish
515                 sgSetVec4( color, 0.9, 0.6, 0.2, bright - factor * 0.2 );
516             } else {
517                 // 5% chance of redish
518                 sgSetVec4( color, 0.9, 0.2, 0.2, bright - factor * 0.2 );
519             }
520             cl->add( color );
521         }
522     }
523
524     // create ssg leaf
525     ssgLeaf *leaf = 
526         new ssgVtxTable ( GL_POINTS, vl, nl, tl, cl );
527
528     // assign state
529     SGMaterial *mat = matlib->find( "GROUND_LIGHTS" );
530     leaf->setState( mat->get_state() );
531     leaf->setCallback( SSG_CALLBACK_PREDRAW, fgLightsPredraw );
532     leaf->setCallback( SSG_CALLBACK_POSTDRAW, fgLightsPostdraw );
533
534     return leaf;
535 }
536
537
538 bool FGTileEntry::obj_load( const string& path,
539                             ssgBranch* geometry,
540                             ssgBranch* rwy_lights,
541                             ssgBranch* taxi_lights,
542                             ssgVertexArray* ground_lights, bool is_base )
543 {
544     Point3D c;                  // returned center point
545     double br;                  // returned bounding radius
546
547     bool use_random_objects =
548         fgGetBool("/sim/rendering/random-objects", true);
549
550     // try loading binary format
551     if ( sgBinObjLoad( path, is_base,
552                        &c, &br, globals->get_matlib(), use_random_objects,
553                        geometry, rwy_lights, taxi_lights, ground_lights ) )
554     {
555         if ( is_base ) {
556             center = c;
557             bounding_radius = br;
558         }
559     }
560
561     return (geometry != NULL);
562 }
563
564
565 void
566 FGTileEntry::load( const string &base_path, bool is_base )
567 {
568     SG_LOG( SG_TERRAIN, SG_INFO, "load() base search path = "
569             << base_path );
570
571     bool found_tile_base = false;
572
573     string_list search = sgPathSplit( base_path );
574
575     // obj_load() will generate ground lighting for us ...
576     ssgVertexArray *light_pts = new ssgVertexArray( 100 );
577
578     ssgBranch* new_tile = new ssgBranch;
579
580     unsigned int i = 0;
581     while ( i < search.size() && !found_tile_base ) {
582
583         // Generate names for later use
584         string index_str = tile_bucket.gen_index_str();
585
586         SGPath tile_path = search[i];
587         tile_path.append( tile_bucket.gen_base_path() );
588
589         SGPath basename = tile_path;
590         basename.append( index_str );
591         // string path = basename.str();
592
593         SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << basename.str() );
594
595 #define FG_MAX_LIGHTS 1000
596
597         // Check for master .stg (scene terra gear) file
598         SGPath stg_name = basename;
599         stg_name.concat( ".stg" );
600
601         sg_gzifstream in( stg_name.str() );
602
603         if ( in.is_open() ) {
604             string token, name;
605
606             while ( ! in.eof() ) {
607                 in >> token;
608
609                 if ( token == "OBJECT_BASE" ) {
610                     in >> name >> ::skipws;
611                     SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
612                             << " name = " << name );
613
614                     found_tile_base = true;
615
616                     SGPath custom_path = tile_path;
617                     custom_path.append( name );
618
619                     ssgBranch *geometry = new ssgBranch;
620                     if ( obj_load( custom_path.str(),
621                                    geometry, NULL, NULL, light_pts, true ) )
622                     {
623                         new_tile -> addKid( geometry );
624                     } else {
625                         delete geometry;
626                     }
627                 } else if ( token == "OBJECT" ) {
628                     in >> name >> ::skipws;
629                     SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
630                             << " name = " << name );
631
632                     SGPath custom_path = tile_path;
633                     custom_path.append( name );
634
635                     ssgBranch *geometry = new ssgBranch;
636                     ssgBranch *rwy_lights = new ssgBranch;
637                     ssgBranch *taxi_lights = new ssgBranch;
638                     if ( obj_load( custom_path.str(),
639                                    geometry, rwy_lights, taxi_lights,
640                                    NULL, false ) )
641                     {
642                         if ( geometry -> getNumKids() > 0 ) {
643                             new_tile -> addKid( geometry );
644                         } else {
645                             delete geometry;
646                         }
647                         if ( rwy_lights -> getNumKids() > 0 ) {
648                             rwy_lights_transform -> addKid( rwy_lights );
649                         } else {
650                             delete rwy_lights;
651                         }
652                         if ( taxi_lights -> getNumKids() > 0 ) {
653                             taxi_lights_transform -> addKid( taxi_lights );
654                         } else {
655                             delete taxi_lights;
656                         }
657                     } else {
658                         delete geometry;
659                         delete rwy_lights;
660                         delete taxi_lights;
661                     }
662
663                 } else if ( token == "OBJECT_STATIC" ||
664                             token == "OBJECT_SHARED" ) {
665                     // load object info
666                     double lon, lat, elev, hdg;
667                     in >> name >> lon >> lat >> elev >> hdg >> ::skipws;
668                     SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
669                             << " name = " << name 
670                             << " pos = " << lon << ", " << lat
671                             << " elevation = " << elev
672                             << " heading = " << hdg );
673
674                     // object loading is deferred to main render thread,
675                     // but lets figure out the paths right now.
676                     SGPath custom_path;
677                     if ( token == "OBJECT_STATIC" ) {
678                         custom_path= tile_path;
679                     }
680                     custom_path.append( name );
681
682                     sgCoord obj_pos;
683                     WorldCoordinate( &obj_pos, center, lat, lon, elev, hdg );
684                 
685                     ssgTransform *obj_trans = new ssgTransform;
686                     obj_trans->setTransform( &obj_pos );
687
688                     // wire as much of the scene graph together as we can
689                     new_tile->addKid( obj_trans );
690
691                     // bump up the pending models count
692                     pending_models++;
693
694                     // push an entry onto the model load queue
695                     FGDeferredModel *dm
696                         = new FGDeferredModel( custom_path.str(),
697                                                tile_path.str(),
698                                                this, obj_trans );
699                     FGTileMgr::model_ready( dm );
700                 } else if ( token == "OBJECT_TAXI_SIGN" ) {
701                     // load object info
702                     double lon, lat, elev, hdg;
703                     in >> name >> lon >> lat >> elev >> hdg >> ::skipws;
704                     SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
705                             << " name = " << name 
706                             << " pos = " << lon << ", " << lat
707                             << " elevation = " << elev
708                             << " heading = " << hdg );
709
710                     // load the object itself
711                     SGPath custom_path = tile_path;
712                     custom_path.append( name );
713
714                     sgCoord obj_pos;
715                     WorldCoordinate( &obj_pos, center, lat, lon, elev, hdg );
716
717                     ssgTransform *obj_trans = new ssgTransform;
718                     obj_trans->setTransform( &obj_pos );
719
720                     ssgBranch *custom_obj
721                         = sgMakeTaxiSign( globals->get_matlib(),
722                                           custom_path.str(), name );
723
724                     // wire the pieces together
725                     if ( custom_obj != NULL ) {
726                         obj_trans -> addKid( custom_obj );
727                     }
728                     new_tile->addKid( obj_trans );
729                 } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
730                     // load object info
731                     double lon, lat, elev, hdg;
732                     in >> name >> lon >> lat >> elev >> hdg >> ::skipws;
733                     SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
734                             << " name = " << name 
735                             << " pos = " << lon << ", " << lat
736                             << " elevation = " << elev
737                             << " heading = " << hdg );
738
739                     // load the object itself
740                     SGPath custom_path = tile_path;
741                     custom_path.append( name );
742
743                     sgCoord obj_pos;
744                     WorldCoordinate( &obj_pos, center, lat, lon, elev, hdg );
745
746                     ssgTransform *obj_trans = new ssgTransform;
747                     obj_trans->setTransform( &obj_pos );
748
749                     ssgBranch *custom_obj
750                         = sgMakeRunwaySign( globals->get_matlib(),
751                                             custom_path.str(), name );
752
753                     // wire the pieces together
754                     if ( custom_obj != NULL ) {
755                         obj_trans -> addKid( custom_obj );
756                     }
757                     new_tile->addKid( obj_trans );
758                 } else if ( token == "RWY_LIGHTS" ) {
759                     double lon, lat, hdg, len, width;
760                     string common, end1, end2;
761                     in >> lon >> lat >> hdg >> len >> width
762                        >> common >> end1 >> end2;
763                     SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
764                             << " pos = " << lon << ", " << lat
765                             << " hdg = " << hdg
766                             << " size = " << len << ", " << width
767                             << " codes = " << common << " "
768                             << end1 << " " << end2 );
769                 } else {
770                     SG_LOG( SG_TERRAIN, SG_ALERT,
771                             "Unknown token " << token << " in "
772                             << stg_name.str() );
773                     in >> ::skipws;
774                 }
775             }
776         }
777
778         i++;
779     }
780
781     if ( !found_tile_base ) {
782         // no tile base found, generate an ocean tile on the fly for
783         // this area
784         ssgBranch *geometry = new ssgBranch;
785         Point3D c;
786         double br;
787         if ( sgGenTile( search[0], tile_bucket, &c, &br,
788                         globals->get_matlib(), geometry ) )
789         {
790             center = c;
791             bounding_radius = br;
792             new_tile -> addKid( geometry );
793         } else {
794             delete geometry;
795             SG_LOG( SG_TERRAIN, SG_ALERT,
796                     "Warning: failed to generate ocean tile!" );
797         }
798     }
799
800     if ( new_tile != NULL ) {
801         terra_range->addKid( new_tile );
802     }
803
804     terra_transform->addKid( terra_range );
805
806     // calculate initial tile offset
807     SetOffset( globals->get_scenery()->get_center() );
808     sgCoord sgcoord;
809     sgSetCoord( &sgcoord,
810                 offset.x(), offset.y(), offset.z(),
811                 0.0, 0.0, 0.0 );
812     terra_transform->setTransform( &sgcoord );
813     // terrain->addKid( terra_transform );
814
815     // Add ground lights to scene graph if any exist
816     gnd_lights_transform = NULL;
817     gnd_lights_range = NULL;
818     if ( light_pts->getNum() ) {
819         SG_LOG( SG_TERRAIN, SG_DEBUG, "generating lights" );
820         gnd_lights_transform = new ssgTransform;
821         gnd_lights_range = new ssgRangeSelector;
822         gnd_lights_brightness = new ssgSelector;
823         ssgLeaf *lights;
824
825         lights = gen_lights( globals->get_matlib(), light_pts, 4, 0.7 );
826         gnd_lights_brightness->addKid( lights );
827
828         lights = gen_lights( globals->get_matlib(), light_pts, 2, 0.85 );
829         gnd_lights_brightness->addKid( lights );
830
831         lights = gen_lights( globals->get_matlib(), light_pts, 1, 1.0 );
832         gnd_lights_brightness->addKid( lights );
833
834         gnd_lights_range->addKid( gnd_lights_brightness );
835         gnd_lights_transform->addKid( gnd_lights_range );
836         gnd_lights_transform->setTransform( &sgcoord );
837     }
838
839     // Update runway lights transform
840     if ( rwy_lights_transform->getNumKids() > 0 ) {
841         rwy_lights_transform->setTransform( &sgcoord );
842     }
843
844      // Update taxi lights transform
845     if ( taxi_lights_transform->getNumKids() > 0 ) {
846         taxi_lights_transform->setTransform( &sgcoord );
847     }
848 }
849
850
851 void
852 FGTileEntry::add_ssg_nodes( ssgBranch* terrain_branch,
853                             ssgBranch* gnd_lights_branch,
854                             ssgBranch* rwy_lights_branch,
855                             ssgBranch* taxi_lights_branch )
856 {
857     // bump up the ref count so we can remove this later without
858     // having ssg try to free the memory.
859     terra_transform->ref();
860     terrain_branch->addKid( terra_transform );
861
862     SG_LOG( SG_TERRAIN, SG_DEBUG,
863             "connected a tile into scene graph.  terra_transform = "
864             << terra_transform );
865     SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
866             << terra_transform->getNumParents() );
867
868     if ( gnd_lights_transform != NULL ) {
869         // bump up the ref count so we can remove this later without
870         // having ssg try to free the memory.
871         gnd_lights_transform->ref();
872         gnd_lights_branch->addKid( gnd_lights_transform );
873     }
874
875     if ( rwy_lights_transform != NULL ) {
876         // bump up the ref count so we can remove this later without
877         // having ssg try to free the memory.
878         rwy_lights_selector->ref();
879         rwy_lights_selector->addKid( rwy_lights_transform );
880         rwy_lights_branch->addKid( rwy_lights_selector );
881     }
882
883     if ( taxi_lights_transform != NULL ) {
884         // bump up the ref count so we can remove this later without
885         // having ssg try to free the memory.
886         taxi_lights_selector->ref();
887         taxi_lights_selector->addKid( taxi_lights_transform );
888         taxi_lights_branch->addKid( taxi_lights_selector );
889     }
890
891     loaded = true;
892 }
893
894
895 void
896 FGTileEntry::disconnect_ssg_nodes()
897 {
898     SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting ssg nodes" );
899
900     if ( ! loaded ) {
901         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
902     } else {
903         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile!  terra_transform = " << terra_transform );
904     }
905         
906     // find the terrain branch parent
907     int pcount = terra_transform->getNumParents();
908     if ( pcount > 0 ) {
909         // find the first parent (should only be one)
910         ssgBranch *parent = terra_transform->getParent( 0 ) ;
911         if( parent ) {
912             // disconnect the tile (we previously ref()'d it so it
913             // won't get freed now)
914             parent->removeKid( terra_transform );
915         } else {
916             SG_LOG( SG_TERRAIN, SG_ALERT,
917                     "parent pointer is NULL!  Dying" );
918             exit(-1);
919         }
920     } else {
921         SG_LOG( SG_TERRAIN, SG_ALERT,
922                 "Parent count is zero for an ssg tile!  Dying" );
923         exit(-1);
924     }
925
926     // find the ground lighting branch
927     if ( gnd_lights_transform ) {
928         pcount = gnd_lights_transform->getNumParents();
929         if ( pcount > 0 ) {
930             // find the first parent (should only be one)
931             ssgBranch *parent = gnd_lights_transform->getParent( 0 ) ;
932             if( parent ) {
933                 // disconnect the light branch (we previously ref()'d
934                 // it so it won't get freed now)
935                 parent->removeKid( gnd_lights_transform );
936             } else {
937                 SG_LOG( SG_TERRAIN, SG_ALERT,
938                         "parent pointer is NULL!  Dying" );
939                 exit(-1);
940             }
941         } else {
942             SG_LOG( SG_TERRAIN, SG_ALERT,
943                     "Parent count is zero for an ssg light tile!  Dying" );
944             exit(-1);
945         }
946     }
947
948     // find the runway lighting branch
949     if ( rwy_lights_transform ) {
950         pcount = rwy_lights_transform->getNumParents();
951         if ( pcount > 0 ) {
952             // find the first parent (should only be one)
953             ssgBranch *parent = rwy_lights_transform->getParent( 0 ) ;
954             if( parent ) {
955                 // disconnect the light branch (we previously ref()'d
956                 // it so it won't get freed now)
957                 parent->removeKid( rwy_lights_transform );
958             } else {
959                 SG_LOG( SG_TERRAIN, SG_ALERT,
960                         "parent pointer is NULL!  Dying" );
961                 exit(-1);
962             }
963         } else {
964             SG_LOG( SG_TERRAIN, SG_ALERT,
965                     "Parent count is zero for an ssg light tile!  Dying" );
966             exit(-1);
967         }
968     }
969
970     // find the taxi lighting branch
971     if ( taxi_lights_transform ) {
972         pcount = taxi_lights_transform->getNumParents();
973         if ( pcount > 0 ) {
974             // find the first parent (should only be one)
975             ssgBranch *parent = taxi_lights_transform->getParent( 0 ) ;
976             if( parent ) {
977                 // disconnect the light branch (we previously ref()'d
978                 // it so it won't get freed now)
979                 parent->removeKid( taxi_lights_transform );
980             } else {
981                 SG_LOG( SG_TERRAIN, SG_ALERT,
982                         "parent pointer is NULL!  Dying" );
983                 exit(-1);
984             }
985         } else {
986             SG_LOG( SG_TERRAIN, SG_ALERT,
987                     "Parent count is zero for an ssg light tile!  Dying" );
988             exit(-1);
989         }
990     }
991 }