]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tileentry.cxx
Modified Files:
[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  - http://www.flightgear.org/~curt
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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29 #include <plib/ul.h>
30 #include <Main/main.hxx>
31
32
33 #include STL_STRING
34
35 #include <osg/Array>
36 #include <osg/Geometry>
37 #include <osg/Geode>
38 #include <osg/LOD>
39 #include <osg/MatrixTransform>
40 #include <osg/NodeCallback>
41 #include <osg/Switch>
42
43 #include <simgear/bucket/newbucket.hxx>
44 #include <simgear/debug/logstream.hxx>
45 #include <simgear/math/polar3d.hxx>
46 #include <simgear/math/sg_geodesy.hxx>
47 #include <simgear/math/sg_random.h>
48 #include <simgear/misc/sgstream.hxx>
49 #include <simgear/scene/material/mat.hxx>
50 #include <simgear/scene/material/matlib.hxx>
51 #include <simgear/scene/tgdb/apt_signs.hxx>
52 #include <simgear/scene/tgdb/obj.hxx>
53 #include <simgear/scene/model/placementtrans.hxx>
54
55 #include <Aircraft/aircraft.hxx>
56 #include <Include/general.hxx>
57 #include <Main/fg_props.hxx>
58 #include <Main/globals.hxx>
59 #include <Main/viewer.hxx>
60 #include <Scenery/scenery.hxx>
61 #include <Time/light.hxx>
62
63 #include "tileentry.hxx"
64 #include "tilemgr.hxx"
65
66 SG_USING_STD(string);
67
68
69 // Constructor
70 FGTileEntry::FGTileEntry ( const SGBucket& b )
71     : center( Point3D( 0.0 ) ),
72       tile_bucket( b ),
73       terra_transform( new SGPlacementTransform ),
74       vasi_lights_transform( new SGPlacementTransform ),
75       rwy_lights_transform( new SGPlacementTransform ),
76       taxi_lights_transform( new SGPlacementTransform ),
77       terra_range( new osg::LOD ),
78       vasi_lights_selector( new osg::Switch ),
79       rwy_lights_selector( new osg::Switch ),
80       taxi_lights_selector( new osg::Switch ),
81       loaded(false),
82       pending_models(0),
83       is_inner_ring(false),
84       free_tracker(0)
85 {
86     // update the contents
87     // if ( vec3_ptrs.size() || vec2_ptrs.size() || index_ptrs.size() ) {
88     //     SG_LOG( SG_TERRAIN, SG_ALERT, 
89     //             "Attempting to overwrite existing or"
90     //             << " not properly freed leaf data." );
91     //     exit(-1);
92     // }
93 }
94
95
96 // Destructor
97 FGTileEntry::~FGTileEntry () {
98     // cout << "nodes = " << nodes.size() << endl;;
99     // delete[] nodes;
100 }
101
102 static void WorldCoordinate( osg::Matrix& obj_pos, Point3D center, double lat,
103                              double lon, double elev, double hdg )
104 {
105     double lon_rad = lon * SGD_DEGREES_TO_RADIANS;
106     double lat_rad = lat * SGD_DEGREES_TO_RADIANS;
107     double hdg_rad = hdg * SGD_DEGREES_TO_RADIANS;
108
109     // setup transforms
110     Point3D geod( lon_rad, lat_rad, elev );
111         
112     Point3D world_pos = sgGeodToCart( geod );
113     Point3D offset = world_pos - center;
114
115     sgMat4 mat;
116
117     SGfloat sin_lat = (SGfloat)sin( lat_rad );
118     SGfloat cos_lat = (SGfloat)cos( lat_rad );
119     SGfloat cos_lon = (SGfloat)cos( lon_rad );
120     SGfloat sin_lon = (SGfloat)sin( lon_rad );
121     SGfloat sin_hdg = (SGfloat)sin( hdg_rad ) ;
122     SGfloat cos_hdg = (SGfloat)cos( hdg_rad ) ;
123
124     mat[0][0] =  cos_hdg * (SGfloat)sin_lat * (SGfloat)cos_lon - sin_hdg * (SGfloat)sin_lon;
125     mat[0][1] =  cos_hdg * (SGfloat)sin_lat * (SGfloat)sin_lon + sin_hdg * (SGfloat)cos_lon;
126     mat[0][2] = -cos_hdg * (SGfloat)cos_lat;
127     mat[0][3] =  SG_ZERO;
128
129     mat[1][0] = -sin_hdg * (SGfloat)sin_lat * (SGfloat)cos_lon - cos_hdg * (SGfloat)sin_lon;
130     mat[1][1] = -sin_hdg * (SGfloat)sin_lat * (SGfloat)sin_lon + cos_hdg * (SGfloat)cos_lon;
131     mat[1][2] =  sin_hdg * (SGfloat)cos_lat;
132     mat[1][3] =  SG_ZERO;
133
134     mat[2][0] = (SGfloat)cos_lat * (SGfloat)cos_lon;
135     mat[2][1] = (SGfloat)cos_lat * (SGfloat)sin_lon;
136     mat[2][2] = (SGfloat)sin_lat;
137     mat[2][3] =  SG_ZERO;
138
139     mat[3][0] = offset.x();
140     mat[3][1] = offset.y();
141     mat[3][2] = offset.z();
142     mat[3][3] = SG_ONE ;
143
144     for (unsigned i = 0; i < 4; ++i)
145       for (unsigned j = 0; j < 4; ++j)
146         obj_pos(i, j) = mat[i][j];
147 }
148
149
150 // recurse an ssg tree and call removeChild() on every node from the
151 // bottom up.  Leaves the original branch in existance, but empty so
152 // it can be removed by the calling routine.
153 // static void my_remove_branch( osg::Group * branch ) {
154 //     branch->removeChildren(0, branch->getNumChildren());
155 // }
156
157
158 // Free "n" leaf elements of an ssg tree.  returns the number of
159 // elements freed.  An empty branch node is considered a leaf.  This
160 // is intended to spread the load of freeing a complex tile out over
161 // several frames.
162 static int fgPartialFreeSSGtree( osg::Group *b, int n ) {
163     int num_deletes = 0;
164
165     b->removeChildren(0, b->getNumChildren());
166
167 //     if ( n > 0 ) {
168 //         // we still have some delete budget left
169 //         // if ( b->getNumChilds() > 100 ) {
170 //         //     cout << "large family = " << b->getNumChilds() << endl;
171 //         // }
172 //         // deleting in reverse would help if my plib patch get's
173 //         // applied, but for now it will make things slower.
174 //         // for ( int i = b->getNumChilds() - 1; i >= 0 ; --i ) {
175 //         for ( int i = 0; i < b->getNumChildren(); ++i ) {
176 //             ssgEntity *kid = b->getChild(i);
177 //             if ( kid->isAKindOf( ssgTypeBranch() ) && kid->getRef() <= 1 ) {
178 //                 int result = fgPartialFreeSSGtree( (osg::Group *)kid, n );
179 //                 num_deletes += result;
180 //                 n -= result;
181 //                 if ( n < 0 ) {
182 //                     break;
183 //                 }
184 //             }
185 //             // remove the kid if (a) it is now empty -or- (b) it's ref
186 //             // count is > zero at which point we don't care if it's
187 //             // empty, we don't want to touch it's contents.
188 //             if ( kid->getNumChildren() == 0 || kid->getRef() > 1 ) {
189 //                 b->removeChild( kid );
190 //                 num_deletes++;
191 //                 n--;
192 //             }
193 //         }
194 //     }
195
196     return num_deletes;
197 }
198
199
200 // Clean up the memory used by this tile and delete the arrays used by
201 // ssg as well as the whole ssg branch
202 bool FGTileEntry::free_tile() {
203     int delete_size = 100;
204     SG_LOG( SG_TERRAIN, SG_DEBUG,
205             "FREEING TILE = (" << tile_bucket << ")" );
206
207     SG_LOG( SG_TERRAIN, SG_DEBUG, "(start) free_tracker = " << free_tracker );
208     
209     if ( !(free_tracker & NODES) ) {
210         free_tracker |= NODES;
211     } else if ( !(free_tracker & VEC_PTRS) ) {
212         free_tracker |= VEC_PTRS;
213     } else if ( !(free_tracker & TERRA_NODE) ) {
214         // delete the terrain branch (this should already have been
215         // disconnected from the scene graph)
216         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING terra_transform" );
217         if ( fgPartialFreeSSGtree( terra_transform.get(), delete_size ) == 0 ) {
218             terra_transform = 0;
219             free_tracker |= TERRA_NODE;
220         }
221     } else if ( !(free_tracker & GROUND_LIGHTS) && gnd_lights_transform.get() ) {
222         // delete the terrain lighting branch (this should already have been
223         // disconnected from the scene graph)
224         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING gnd_lights_transform" );
225         if ( fgPartialFreeSSGtree( gnd_lights_transform.get(), delete_size ) == 0 ) {
226             gnd_lights_transform = 0;
227             free_tracker |= GROUND_LIGHTS;
228         }
229     } else if ( !(free_tracker & VASI_LIGHTS) && vasi_lights_selector.get() ) {
230         // delete the runway lighting branch (this should already have
231         // been disconnected from the scene graph)
232         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING vasi_lights_selector" );
233         if ( fgPartialFreeSSGtree( vasi_lights_selector.get(), delete_size ) == 0 ) {
234             vasi_lights_selector = 0;
235             free_tracker |= VASI_LIGHTS;
236         }
237     } else if ( !(free_tracker & RWY_LIGHTS) && rwy_lights_selector.get() ) {
238         // delete the runway lighting branch (this should already have
239         // been disconnected from the scene graph)
240         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING rwy_lights_selector" );
241         if ( fgPartialFreeSSGtree( rwy_lights_selector.get(), delete_size ) == 0 ) {
242             rwy_lights_selector = 0;
243             free_tracker |= RWY_LIGHTS;
244         }
245     } else if ( !(free_tracker & TAXI_LIGHTS) && taxi_lights_selector.get() ) {
246         // delete the taxi lighting branch (this should already have been
247         // disconnected from the scene graph)
248         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING taxi_lights_selector" );
249         if ( fgPartialFreeSSGtree( taxi_lights_selector.get(), delete_size ) == 0 ) {
250             taxi_lights_selector = 0;
251             free_tracker |= TAXI_LIGHTS;
252         }
253     } else if ( !(free_tracker & LIGHTMAPS) ) {
254         free_tracker |= LIGHTMAPS;
255     } else {
256         return true;
257     }
258
259     SG_LOG( SG_TERRAIN, SG_DEBUG, "(end) free_tracker = " << free_tracker );
260
261     // if we fall down to here, we still have work todo, return false
262     return false;
263 }
264
265
266 // Update the ssg transform node for this tile so it can be
267 // properly drawn relative to our (0,0,0) point
268 void FGTileEntry::prep_ssg_node( const Point3D& p, sgVec3 up, float vis) {
269     if ( !loaded ) return;
270
271     // visibility can change from frame to frame so we update the
272     // range selector cutoff's each time.
273     terra_range->setRange( 0, 0, vis + bounding_radius );
274
275     if ( gnd_lights_range.get() ) {
276         gnd_lights_range->setRange( 0, 0, vis * 1.5 + bounding_radius );
277     }
278
279     SGVec3d lt_trans(center.x(), center.y(), center.z());
280
281     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
282     if ( gnd_lights_transform.get() ) {
283         // we need to lift the lights above the terrain to avoid
284         // z-buffer fighting.  We do this based on our altitude and
285         // the distance this tile is away from scenery center.
286
287         // we expect 'up' to be a unit vector coming in, but since we
288         // modify the value of lift_vec, we need to create a local
289         // copy.
290         SGVec3f lift_vec(up);
291   
292         double agl;
293         agl = globals->get_current_view()->getAltitudeASL_ft()*SG_FEET_TO_METER
294           - globals->get_current_view()->getSGLocation()->get_cur_elev_m();
295
296         // Compute the distance of the scenery center from the view position.
297         double dist = center.distance3D(p);
298
299         if ( general.get_glDepthBits() > 16 ) {
300             lift_vec *= 10.0 + agl / 100.0 + dist / 10000;
301         } else {
302             lift_vec *= 10.0 + agl / 20.0 + dist / 5000;
303         }
304
305         gnd_lights_transform->setTransform( lt_trans + toVec3d(lift_vec) );
306
307         // select which set of lights based on sun angle
308         float sun_angle = l->get_sun_angle() * SGD_RADIANS_TO_DEGREES;
309         if ( sun_angle > 95 ) {
310             gnd_lights_brightness->setSingleChildOn(2);
311         } else if ( sun_angle > 92 ) {
312             gnd_lights_brightness->setSingleChildOn(1);
313         } else if ( sun_angle > 89 ) {
314             gnd_lights_brightness->setSingleChildOn(0);
315         } else {
316             gnd_lights_brightness->setAllChildrenOff();
317         }
318     }
319
320     if ( rwy_lights_transform.get() ) {
321         // turn runway lights on/off based on sun angle and visibility
322         float sun_angle = l->get_sun_angle() * SGD_RADIANS_TO_DEGREES;
323         if ( sun_angle > 85 ||
324              (fgGetDouble("/environment/visibility-m") < 5000.0) ) {
325             rwy_lights_selector->setAllChildrenOn();
326         } else {
327             rwy_lights_selector->setAllChildrenOff();
328         }
329     }
330
331     if ( taxi_lights_transform.get() ) {
332         // turn taxi lights on/off based on sun angle and visibility
333         float sun_angle = l->get_sun_angle() * SGD_RADIANS_TO_DEGREES;
334         if ( sun_angle > 85 ||
335              (fgGetDouble("/environment/visibility-m") < 5000.0) ) {
336             taxi_lights_selector->setAllChildrenOn();
337         } else {
338             taxi_lights_selector->setAllChildrenOff();
339         }
340     }
341 }
342
343
344 osg::Node*
345 FGTileEntry::gen_lights( SGMaterialLib *matlib, osg::Vec3Array *lights,
346                          int inc, float bright )
347 {
348     // generate a repeatable random seed
349     sg_srandom( (unsigned)(*lights)[0][0] );
350
351     // Allocate ssg structure
352     osg::Vec3Array *vl = new osg::Vec3Array;
353     osg::Vec4Array *cl = new osg::Vec4Array;
354
355     for ( unsigned i = 0; i < lights->size(); ++i ) {
356         // this loop is slightly less efficient than it otherwise
357         // could be, but we want a red light to always be red, and a
358         // yellow light to always be yellow, etc. so we are trying to
359         // preserve the random sequence.
360         float zombie = sg_random();
361         if ( i % inc == 0 ) {
362             vl->push_back( (*lights)[i] );
363
364             // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
365             float factor = sg_random();
366             factor *= factor;
367
368             osg::Vec4 color;
369             if ( zombie > 0.5 ) {
370                 // 50% chance of yellowish
371                 color = osg::Vec4( 0.9, 0.9, 0.3, bright - factor * 0.2 );
372             } else if ( zombie > 0.15 ) {
373                 // 35% chance of whitish
374                 color = osg::Vec4( 0.9, 0.9, 0.8, bright - factor * 0.2 );
375             } else if ( zombie > 0.05 ) {
376                 // 10% chance of orangish
377                 color = osg::Vec4( 0.9, 0.6, 0.2, bright - factor * 0.2 );
378             } else {
379                 // 5% chance of redish
380                 color = osg::Vec4( 0.9, 0.2, 0.2, bright - factor * 0.2 );
381             }
382             cl->push_back( color );
383         }
384     }
385
386     // create ssg leaf
387     osg::Geometry* geometry = new osg::Geometry;
388     geometry->setVertexArray(vl);
389     geometry->setColorArray(cl);
390     geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
391     geometry->addPrimitiveSet(new osg::DrawArrays(GL_POINTS, 0, vl->size()));
392     osg::Geode* geode = new osg::Geode;
393     geode->addDrawable(geometry);
394
395     // assign state
396     SGMaterial *mat = matlib->find( "GROUND_LIGHTS" );
397     geode->setStateSet(mat->get_state());
398
399     return geode;
400 }
401
402
403 bool FGTileEntry::obj_load( const string& path,
404                             osg::Group *geometry,
405                             osg::Group *vasi_lights,
406                             osg::Group *rwy_lights,
407                             osg::Group *taxi_lights,
408                             osg::Vec3Array *ground_lights, bool is_base )
409 {
410     Point3D c;                  // returned center point
411     double br;                  // returned bounding radius
412
413     bool use_random_objects =
414         fgGetBool("/sim/rendering/random-objects", true);
415
416     // try loading binary format
417     if ( SGBinObjLoad( path, is_base,
418                        &c, &br, globals->get_matlib(), use_random_objects,
419                        geometry, vasi_lights, rwy_lights, taxi_lights,
420                        ground_lights ) )
421     {
422         if ( is_base ) {
423             center = c;
424             bounding_radius = br;
425         }
426     }
427
428     return (geometry != NULL);
429 }
430
431
432 typedef enum {
433     OBJECT,
434     OBJECT_SHARED,
435     OBJECT_STATIC,
436     OBJECT_SIGN,
437     OBJECT_RUNWAY_SIGN
438 } object_type;
439
440
441 // storage class for deferred object processing in FGTileEntry::load()
442 struct Object {
443     Object(object_type t, const string& token, const SGPath& p, istream& in)
444         : type(t), path(p)
445     {
446         in >> name;
447         if (type != OBJECT)
448             in >> lon >> lat >> elev >> hdg;
449         in >> ::skipeol;
450
451         if (type == OBJECT)
452             SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  " << name);
453         else
454             SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  " << name << "  lon=" <<
455                     lon << "  lat=" << lat << "  elev=" << elev << "  hdg=" << hdg);
456     }
457     object_type type;
458     string name;
459     SGPath path;
460     double lon, lat, elev, hdg;
461 };
462
463
464 void
465 FGTileEntry::load( const string_list &path_list, bool is_base )
466 {
467     bool found_tile_base = false;
468
469     SGPath object_base;
470     vector<const Object*> objects;
471
472     string index_str = tile_bucket.gen_index_str();
473     SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
474
475     // scan and parse all files and store information
476     for (unsigned int i = 0; i < path_list.size(); i++) {
477         // If we found a terrain tile in Terrain/, we have to process the
478         // Objects/ dir in the same group, too, before we can stop scanning.
479         // FGGlobals::set_fg_scenery() inserts an empty string to path_list
480         // as marker.
481         if (path_list[i].empty()) {
482             if (found_tile_base)
483                 break;
484             else
485                 continue;
486         }
487
488         bool has_base = false;
489
490         SGPath tile_path = path_list[i];
491         tile_path.append( tile_bucket.gen_base_path() );
492
493         SGPath basename = tile_path;
494         basename.append( index_str );
495
496         SG_LOG( SG_TERRAIN, SG_INFO, "  Trying " << basename.str() );
497
498
499         // Check for master .stg (scene terra gear) file
500         SGPath stg_name = basename;
501         stg_name.concat( ".stg" );
502
503         sg_gzifstream in( stg_name.str() );
504         if ( !in.is_open() )
505             continue;
506
507         while ( ! in.eof() ) {
508             string token;
509             in >> token;
510
511             if ( token[0] == '#' ) {
512                in >> ::skipeol;
513                continue;
514             }
515                             // Load only once (first found)
516             if ( token == "OBJECT_BASE" ) {
517                 string name;
518                 in >> name >> ::skipws;
519                 SG_LOG( SG_TERRAIN, SG_INFO, "    " << token << " " << name );
520
521                 if (!found_tile_base) {
522                     found_tile_base = true;
523                     has_base = true;
524
525                     object_base = tile_path;
526                     object_base.append(name);
527
528                 } else
529                     SG_LOG(SG_TERRAIN, SG_INFO, "    (skipped)");
530
531                             // Load only if base is not in another file
532             } else if ( token == "OBJECT" ) {
533                 if (!found_tile_base || has_base)
534                     objects.push_back(new Object(OBJECT, token, tile_path, in));
535                 else {
536                     string name;
537                     in >> name >> ::skipeol;
538                     SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  "
539                             << name << "  (skipped)");
540                 }
541
542                             // Always OK to load
543             } else if ( token == "OBJECT_STATIC" ) {
544                 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
545
546             } else if ( token == "OBJECT_SHARED" ) {
547                 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
548
549             } else if ( token == "OBJECT_SIGN" ) {
550                 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
551
552             } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
553                 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
554
555             } else {
556                 SG_LOG( SG_TERRAIN, SG_DEBUG,
557                         "Unknown token '" << token << "' in " << stg_name.str() );
558                 in >> ::skipws;
559             }
560         }
561     }
562
563
564     // obj_load() will generate ground lighting for us ...
565     osg::ref_ptr<osg::Vec3Array> light_pts = new osg::Vec3Array;
566     osg::Group* new_tile = new osg::Group;
567
568
569     if (found_tile_base) {
570         // load tile if found ...
571         osg::ref_ptr<osg::Group> geometry = new osg::Group;
572         if ( obj_load( object_base.str(), geometry.get(),
573                        NULL, NULL, NULL, light_pts.get(), true ) ) {
574             new_tile -> addChild( geometry.get() );
575         }
576
577     } else {
578         // ... or generate an ocean tile on the fly
579         SG_LOG(SG_TERRAIN, SG_INFO, "  Generating ocean tile");
580         osg::ref_ptr<osg::Group> geometry = new osg::Group;
581         Point3D c;
582         double br;
583         if ( SGGenTile( path_list[0], tile_bucket, &c, &br,
584                         globals->get_matlib(), geometry.get() ) ) {
585             center = c;
586             bounding_radius = br;
587             new_tile -> addChild( geometry.get() );
588         } else {
589             SG_LOG( SG_TERRAIN, SG_ALERT,
590                     "Warning: failed to generate ocean tile!" );
591         }
592     }
593
594
595     // now that we have a valid center, process all the objects
596     for (unsigned int j = 0; j < objects.size(); j++) {
597         const Object *obj = objects[j];
598
599         if (obj->type == OBJECT) {
600             SGPath custom_path = obj->path;
601             custom_path.append( obj->name );
602
603             osg::ref_ptr<osg::Group> geometry = new osg::Group;
604             osg::ref_ptr<osg::Group> vasi_lights = new osg::Group;
605             osg::ref_ptr<osg::Group> rwy_lights = new osg::Group;
606             osg::ref_ptr<osg::Group> taxi_lights = new osg::Group;
607
608             if ( obj_load( custom_path.str(),
609                            geometry.get(), vasi_lights.get(), rwy_lights.get(),
610                            taxi_lights.get(), NULL, false ) ) {
611
612                 if ( geometry -> getNumChildren() > 0 ) {
613                     new_tile -> addChild( geometry.get() );
614                 }
615
616                 if ( vasi_lights -> getNumChildren() > 0 )
617                     vasi_lights_transform -> addChild( vasi_lights.get() );
618
619                 if ( rwy_lights -> getNumChildren() > 0 )
620                     rwy_lights_transform -> addChild( rwy_lights.get() );
621
622                 if ( taxi_lights -> getNumChildren() > 0 )
623                     taxi_lights_transform -> addChild( taxi_lights.get() );
624             }
625
626
627         } else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
628             // object loading is deferred to main render thread,
629             // but lets figure out the paths right now.
630             SGPath custom_path;
631             if ( obj->type == OBJECT_STATIC ) {
632                 custom_path = obj->path;
633             } else {
634                 custom_path = globals->get_fg_root();
635             }
636             custom_path.append( obj->name );
637
638             osg::Matrix obj_pos;
639             WorldCoordinate( obj_pos, center, obj->lat, obj->lon, obj->elev, obj->hdg );
640
641             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
642             obj_trans->setMatrix( obj_pos );
643
644             // wire as much of the scene graph together as we can
645             new_tile->addChild( obj_trans );
646             pending_models++;
647
648             // push an entry onto the model load queue
649             FGDeferredModel *dm
650                 = new FGDeferredModel( custom_path.str(),
651                                        obj->path.str(),
652                                        tile_bucket,
653                                        this, obj_trans,
654                                        obj->type == OBJECT_SHARED );
655             FGTileMgr::model_ready( dm );
656
657
658         } else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
659             // load the object itself
660             SGPath custom_path = obj->path;
661             custom_path.append( obj->name );
662
663             osg::Matrix obj_pos;
664             WorldCoordinate( obj_pos, center, obj->lat, obj->lon, obj->elev, obj->hdg );
665
666             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
667             obj_trans->setMatrix( obj_pos );
668
669             osg::Node *custom_obj = 0;
670             if (obj->type == OBJECT_SIGN)
671                 custom_obj = SGMakeSign(globals->get_matlib(), custom_path.str(), obj->name);
672             else
673                 custom_obj = SGMakeRunwaySign(globals->get_matlib(), custom_path.str(), obj->name);
674
675             // wire the pieces together
676             if ( custom_obj != NULL ) {
677                 obj_trans -> addChild( custom_obj );
678             }
679             new_tile->addChild( obj_trans );
680
681         }
682         delete obj;
683     }
684
685
686     if ( new_tile != NULL ) {
687         terra_range->addChild( new_tile );
688     }
689
690     terra_transform->addChild( terra_range.get() );
691
692     // calculate initial tile offset
693     SGVec3d sgdTrans(center.x(), center.y(), center.z());
694     terra_transform->setTransform( sgdTrans );
695
696     // Add ground lights to scene graph if any exist
697     gnd_lights_transform = NULL;
698     gnd_lights_range = NULL;
699     if ( light_pts->size() ) {
700         SG_LOG( SG_TERRAIN, SG_DEBUG, "generating lights" );
701         gnd_lights_transform = new SGPlacementTransform;
702         gnd_lights_range = new osg::LOD;
703         gnd_lights_brightness = new osg::Switch;
704         osg::Node *lights;
705
706         lights = gen_lights( globals->get_matlib(), light_pts.get(), 4, 0.7 );
707         gnd_lights_brightness->addChild( lights );
708
709         lights = gen_lights( globals->get_matlib(), light_pts.get(), 2, 0.85 );
710         gnd_lights_brightness->addChild( lights );
711
712         lights = gen_lights( globals->get_matlib(), light_pts.get(), 1, 1.0 );
713         gnd_lights_brightness->addChild( lights );
714
715         gnd_lights_range->addChild( gnd_lights_brightness.get() );
716         gnd_lights_transform->addChild( gnd_lights_range.get() );
717         gnd_lights_transform->setTransform( sgdTrans );
718     }
719
720     // Update vasi lights transform
721     if ( vasi_lights_transform->getNumChildren() > 0 ) {
722         vasi_lights_transform->setTransform( sgdTrans );
723     }
724
725     // Update runway lights transform
726     if ( rwy_lights_transform->getNumChildren() > 0 ) {
727         rwy_lights_transform->setTransform( sgdTrans );
728     }
729
730      // Update taxi lights transform
731     if ( taxi_lights_transform->getNumChildren() > 0 ) {
732         taxi_lights_transform->setTransform( sgdTrans );
733     }
734 }
735
736 void
737 FGTileEntry::add_ssg_nodes( osg::Group *terrain_branch,
738                             osg::Group *gnd_lights_branch,
739                             osg::Group *vasi_lights_branch,
740                             osg::Group *rwy_lights_branch,
741                             osg::Group *taxi_lights_branch )
742 {
743     // bump up the ref count so we can remove this later without
744     // having ssg try to free the memory.
745     terrain_branch->addChild( terra_transform.get() );
746
747     SG_LOG( SG_TERRAIN, SG_DEBUG,
748             "connected a tile into scene graph.  terra_transform = "
749             << terra_transform.get() );
750     SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
751             << terra_transform->getNumParents() );
752
753     if ( gnd_lights_transform.get() != NULL ) {
754         // bump up the ref count so we can remove this later without
755         // having ssg try to free the memory.
756         gnd_lights_branch->addChild( gnd_lights_transform.get() );
757     }
758
759     if ( vasi_lights_transform.get() != NULL ) {
760         // bump up the ref count so we can remove this later without
761         // having ssg try to free the memory.
762         vasi_lights_selector->addChild( vasi_lights_transform.get() );
763         vasi_lights_branch->addChild( vasi_lights_selector.get() );
764     }
765
766     if ( rwy_lights_transform.get() != NULL ) {
767         // bump up the ref count so we can remove this later without
768         // having ssg try to free the memory.
769         rwy_lights_selector->addChild( rwy_lights_transform.get() );
770         rwy_lights_branch->addChild( rwy_lights_selector.get() );
771     }
772
773     if ( taxi_lights_transform.get() != NULL ) {
774         // bump up the ref count so we can remove this later without
775         // having ssg try to free the memory.
776         taxi_lights_selector->addChild( taxi_lights_transform.get() );
777         taxi_lights_branch->addChild( taxi_lights_selector.get() );
778     }
779
780     loaded = true;
781 }
782
783
784 void
785 FGTileEntry::disconnect_ssg_nodes()
786 {
787     SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting ssg nodes" );
788
789     if ( ! loaded ) {
790         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
791     } else {
792         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile!  terra_transform = " << terra_transform.get() );
793     }
794         
795     // find the terrain branch parent
796     int pcount = terra_transform->getNumParents();
797     if ( pcount > 0 ) {
798         // find the first parent (should only be one)
799         osg::Group *parent = terra_transform->getParent( 0 ) ;
800         if( parent ) {
801             // disconnect the tile (we previously ref()'d it so it
802             // won't get freed now)
803             parent->removeChild( terra_transform.get() );
804         } else {
805             SG_LOG( SG_TERRAIN, SG_ALERT,
806                     "parent pointer is NULL!  Dying" );
807             exit(-1);
808         }
809     } else {
810         SG_LOG( SG_TERRAIN, SG_ALERT,
811                 "Parent count is zero for an ssg tile!  Dying" );
812         exit(-1);
813     }
814
815     // find the ground lighting branch
816     if ( gnd_lights_transform.get() ) {
817         pcount = gnd_lights_transform->getNumParents();
818         if ( pcount > 0 ) {
819             // find the first parent (should only be one)
820             osg::Group *parent = gnd_lights_transform->getParent( 0 ) ;
821             if( parent ) {
822                 // disconnect the light branch (we previously ref()'d
823                 // it so it won't get freed now)
824                 parent->removeChild( gnd_lights_transform.get() );
825             } else {
826                 SG_LOG( SG_TERRAIN, SG_ALERT,
827                         "parent pointer is NULL!  Dying" );
828                 exit(-1);
829             }
830         } else {
831             SG_LOG( SG_TERRAIN, SG_ALERT,
832                     "Parent count is zero for an ssg light tile!  Dying" );
833             exit(-1);
834         }
835     }
836
837     // find the vasi lighting branch
838     if ( vasi_lights_transform.get() ) {
839         pcount = vasi_lights_transform->getNumParents();
840         if ( pcount > 0 ) {
841             // find the first parent (should only be one)
842             osg::Group *parent = vasi_lights_transform->getParent( 0 ) ;
843             if( parent ) {
844                 // disconnect the light branch (we previously ref()'d
845                 // it so it won't get freed now)
846                 parent->removeChild( vasi_lights_transform.get() );
847             } else {
848                 SG_LOG( SG_TERRAIN, SG_ALERT,
849                         "parent pointer is NULL!  Dying" );
850                 exit(-1);
851             }
852         } else {
853             SG_LOG( SG_TERRAIN, SG_ALERT,
854                     "Parent count is zero for an ssg light tile!  Dying" );
855             exit(-1);
856         }
857     }
858
859     // find the runway lighting branch
860     if ( rwy_lights_transform.get() ) {
861         pcount = rwy_lights_transform->getNumParents();
862         if ( pcount > 0 ) {
863             // find the first parent (should only be one)
864             osg::Group *parent = rwy_lights_transform->getParent( 0 ) ;
865             if( parent ) {
866                 // disconnect the light branch (we previously ref()'d
867                 // it so it won't get freed now)
868                 parent->removeChild( rwy_lights_transform.get() );
869             } else {
870                 SG_LOG( SG_TERRAIN, SG_ALERT,
871                         "parent pointer is NULL!  Dying" );
872                 exit(-1);
873             }
874         } else {
875             SG_LOG( SG_TERRAIN, SG_ALERT,
876                     "Parent count is zero for an ssg light tile!  Dying" );
877             exit(-1);
878         }
879     }
880
881     // find the taxi lighting branch
882     if ( taxi_lights_transform.get() ) {
883         pcount = taxi_lights_transform->getNumParents();
884         if ( pcount > 0 ) {
885             // find the first parent (should only be one)
886             osg::Group *parent = taxi_lights_transform->getParent( 0 ) ;
887             if( parent ) {
888                 // disconnect the light branch (we previously ref()'d
889                 // it so it won't get freed now)
890                 parent->removeChild( taxi_lights_transform.get() );
891             } else {
892                 SG_LOG( SG_TERRAIN, SG_ALERT,
893                         "parent pointer is NULL!  Dying" );
894                 exit(-1);
895             }
896         } else {
897             SG_LOG( SG_TERRAIN, SG_ALERT,
898                     "Parent count is zero for an ssg light tile!  Dying" );
899             exit(-1);
900         }
901     }
902 }