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