]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tileentry.cxx
ssgSharedPtr.hxx -> SGSharedPtr.hxx
[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 ( vasi_lights_transform.get() ) {
321         // we need to lift the lights above the terrain to avoid
322         // z-buffer fighting.  We do this based on our altitude and
323         // the distance this tile is away from scenery center.
324         SGVec3f lift_vec(up);
325
326         // we fudge agl by 30 meters so that the lifting function
327         // doesn't phase in until we are > 30m agl.
328         double agl;
329         agl = globals->get_current_view()->getAltitudeASL_ft()*SG_FEET_TO_METER
330           - globals->get_current_view()->getSGLocation()->get_cur_elev_m()
331           - 30.0;
332         if ( agl < 0.0 ) {
333             agl = 0.0;
334         }
335         
336         if ( general.get_glDepthBits() > 16 ) {
337             lift_vec *= 0.25 + agl / 400.0 + agl*agl / 5000000.0;
338         } else {
339             lift_vec *= 0.25 + agl / 150.0;
340         }
341
342         vasi_lights_transform->setTransform( lt_trans + toVec3d(lift_vec) );
343
344         // generally, vasi lights are always on
345         vasi_lights_selector->setAllChildrenOn();
346     }
347
348     if ( rwy_lights_transform.get() ) {
349         // we need to lift the lights above the terrain to avoid
350         // z-buffer fighting.  We do this based on our altitude and
351         // the distance this tile is away from scenery center.
352         SGVec3f lift_vec(up);
353
354         // we fudge agl by 30 meters so that the lifting function
355         // doesn't phase in until we are > 30m agl.
356         double agl;
357         agl = globals->get_current_view()->getAltitudeASL_ft()*SG_FEET_TO_METER
358           - globals->get_current_view()->getSGLocation()->get_cur_elev_m()
359           - 30.0;
360         if ( agl < 0.0 ) {
361             agl = 0.0;
362         }
363         
364         if ( general.get_glDepthBits() > 16 ) {
365             lift_vec *= 0.01 + agl / 400.0 + agl*agl / 5000000.0;
366         } else {
367             lift_vec *= 0.25 + agl / 150.0;
368         }
369
370         rwy_lights_transform->setTransform( lt_trans + toVec3d(lift_vec) );
371
372         // turn runway lights on/off based on sun angle and visibility
373         float sun_angle = l->get_sun_angle() * SGD_RADIANS_TO_DEGREES;
374         if ( sun_angle > 85 ||
375              (fgGetDouble("/environment/visibility-m") < 5000.0) ) {
376             rwy_lights_selector->setAllChildrenOn();
377         } else {
378             rwy_lights_selector->setAllChildrenOff();
379         }
380     }
381
382     if ( taxi_lights_transform.get() ) {
383         // we need to lift the lights above the terrain to avoid
384         // z-buffer fighting.  We do this based on our altitude and
385         // the distance this tile is away from scenery center.
386         SGVec3f lift_vec(up);
387
388         // we fudge agl by 30 meters so that the lifting function
389         // doesn't phase in until we are > 30m agl.
390         double agl;
391         agl = globals->get_current_view()->getAltitudeASL_ft()*SG_FEET_TO_METER
392           - globals->get_current_view()->getSGLocation()->get_cur_elev_m()
393           - 30.0;
394         if ( agl < 0.0 ) {
395             agl = 0.0;
396         }
397         
398         if ( general.get_glDepthBits() > 16 ) {
399             lift_vec *= 0.01 + agl / 400.0 + agl*agl / 5000000.0;
400         } else {
401             lift_vec *= 0.25 + agl / 150.0;
402         }
403
404         taxi_lights_transform->setTransform( lt_trans + toVec3d(lift_vec) );
405
406         // turn taxi lights on/off based on sun angle and visibility
407         float sun_angle = l->get_sun_angle() * SGD_RADIANS_TO_DEGREES;
408         if ( sun_angle > 85 ||
409              (fgGetDouble("/environment/visibility-m") < 5000.0) ) {
410             taxi_lights_selector->setAllChildrenOn();
411         } else {
412             taxi_lights_selector->setAllChildrenOff();
413         }
414     }
415 }
416
417
418 osg::Node*
419 FGTileEntry::gen_lights( SGMaterialLib *matlib, osg::Vec3Array *lights,
420                          int inc, float bright )
421 {
422     // generate a repeatable random seed
423     sg_srandom( (unsigned)(*lights)[0][0] );
424
425     // Allocate ssg structure
426     osg::Vec3Array *vl = new osg::Vec3Array;
427     osg::Vec4Array *cl = new osg::Vec4Array;
428
429     for ( unsigned i = 0; i < lights->size(); ++i ) {
430         // this loop is slightly less efficient than it otherwise
431         // could be, but we want a red light to always be red, and a
432         // yellow light to always be yellow, etc. so we are trying to
433         // preserve the random sequence.
434         float zombie = sg_random();
435         if ( i % inc == 0 ) {
436             vl->push_back( (*lights)[i] );
437
438             // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
439             float factor = sg_random();
440             factor *= factor;
441
442             osg::Vec4 color;
443             if ( zombie > 0.5 ) {
444                 // 50% chance of yellowish
445                 color = osg::Vec4( 0.9, 0.9, 0.3, bright - factor * 0.2 );
446             } else if ( zombie > 0.15 ) {
447                 // 35% chance of whitish
448                 color = osg::Vec4( 0.9, 0.9, 0.8, bright - factor * 0.2 );
449             } else if ( zombie > 0.05 ) {
450                 // 10% chance of orangish
451                 color = osg::Vec4( 0.9, 0.6, 0.2, bright - factor * 0.2 );
452             } else {
453                 // 5% chance of redish
454                 color = osg::Vec4( 0.9, 0.2, 0.2, bright - factor * 0.2 );
455             }
456             cl->push_back( color );
457         }
458     }
459
460     // create ssg leaf
461     osg::Geometry* geometry = new osg::Geometry;
462     geometry->setVertexArray(vl);
463     geometry->setColorArray(cl);
464     geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
465     geometry->addPrimitiveSet(new osg::DrawArrays(GL_POINTS, 0, vl->size()));
466     osg::Geode* geode = new osg::Geode;
467     geode->addDrawable(geometry);
468
469     // assign state
470     SGMaterial *mat = matlib->find( "GROUND_LIGHTS" );
471     geode->setStateSet(mat->get_state());
472
473     return geode;
474 }
475
476
477 bool FGTileEntry::obj_load( const string& path,
478                             osg::Group *geometry,
479                             osg::Group *vasi_lights,
480                             osg::Group *rwy_lights,
481                             osg::Group *taxi_lights,
482                             osg::Vec3Array *ground_lights, bool is_base )
483 {
484     Point3D c;                  // returned center point
485     double br;                  // returned bounding radius
486
487     bool use_random_objects =
488         fgGetBool("/sim/rendering/random-objects", true);
489
490     // try loading binary format
491     if ( SGBinObjLoad( path, is_base,
492                        &c, &br, globals->get_matlib(), use_random_objects,
493                        geometry, vasi_lights, rwy_lights, taxi_lights,
494                        ground_lights ) )
495     {
496         if ( is_base ) {
497             center = c;
498             bounding_radius = br;
499         }
500     }
501
502     return (geometry != NULL);
503 }
504
505
506 typedef enum {
507     OBJECT,
508     OBJECT_SHARED,
509     OBJECT_STATIC,
510     OBJECT_SIGN,
511     OBJECT_RUNWAY_SIGN
512 } object_type;
513
514
515 // storage class for deferred object processing in FGTileEntry::load()
516 struct Object {
517     Object(object_type t, const string& token, const SGPath& p, istream& in)
518         : type(t), path(p)
519     {
520         in >> name;
521         if (type != OBJECT)
522             in >> lon >> lat >> elev >> hdg;
523         in >> ::skipeol;
524
525         if (type == OBJECT)
526             SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  " << name);
527         else
528             SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  " << name << "  lon=" <<
529                     lon << "  lat=" << lat << "  elev=" << elev << "  hdg=" << hdg);
530     }
531     object_type type;
532     string name;
533     SGPath path;
534     double lon, lat, elev, hdg;
535 };
536
537
538 void
539 FGTileEntry::load( const string_list &path_list, bool is_base )
540 {
541     bool found_tile_base = false;
542
543     SGPath object_base;
544     vector<const Object*> objects;
545
546     string index_str = tile_bucket.gen_index_str();
547     SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
548
549     // scan and parse all files and store information
550     for (unsigned int i = 0; i < path_list.size(); i++) {
551         // If we found a terrain tile in Terrain/, we have to process the
552         // Objects/ dir in the same group, too, before we can stop scanning.
553         // FGGlobals::set_fg_scenery() inserts an empty string to path_list
554         // as marker.
555         if (path_list[i].empty()) {
556             if (found_tile_base)
557                 break;
558             else
559                 continue;
560         }
561
562         bool has_base = false;
563
564         SGPath tile_path = path_list[i];
565         tile_path.append( tile_bucket.gen_base_path() );
566
567         SGPath basename = tile_path;
568         basename.append( index_str );
569
570         SG_LOG( SG_TERRAIN, SG_INFO, "  Trying " << basename.str() );
571
572
573         // Check for master .stg (scene terra gear) file
574         SGPath stg_name = basename;
575         stg_name.concat( ".stg" );
576
577         sg_gzifstream in( stg_name.str() );
578         if ( !in.is_open() )
579             continue;
580
581         while ( ! in.eof() ) {
582             string token;
583             in >> token;
584
585             if ( token[0] == '#' ) {
586                in >> ::skipeol;
587                continue;
588             }
589                             // Load only once (first found)
590             if ( token == "OBJECT_BASE" ) {
591                 string name;
592                 in >> name >> ::skipws;
593                 SG_LOG( SG_TERRAIN, SG_INFO, "    " << token << " " << name );
594
595                 if (!found_tile_base) {
596                     found_tile_base = true;
597                     has_base = true;
598
599                     object_base = tile_path;
600                     object_base.append(name);
601
602                 } else
603                     SG_LOG(SG_TERRAIN, SG_INFO, "    (skipped)");
604
605                             // Load only if base is not in another file
606             } else if ( token == "OBJECT" ) {
607                 if (!found_tile_base || has_base)
608                     objects.push_back(new Object(OBJECT, token, tile_path, in));
609                 else {
610                     string name;
611                     in >> name >> ::skipeol;
612                     SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  "
613                             << name << "  (skipped)");
614                 }
615
616                             // Always OK to load
617             } else if ( token == "OBJECT_STATIC" ) {
618                 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
619
620             } else if ( token == "OBJECT_SHARED" ) {
621                 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
622
623             } else if ( token == "OBJECT_SIGN" ) {
624                 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
625
626             } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
627                 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
628
629             } else {
630                 SG_LOG( SG_TERRAIN, SG_DEBUG,
631                         "Unknown token '" << token << "' in " << stg_name.str() );
632                 in >> ::skipws;
633             }
634         }
635     }
636
637
638     // obj_load() will generate ground lighting for us ...
639     osg::ref_ptr<osg::Vec3Array> light_pts = new osg::Vec3Array;
640     osg::Group* new_tile = new osg::Group;
641
642
643     if (found_tile_base) {
644         // load tile if found ...
645         osg::ref_ptr<osg::Group> geometry = new osg::Group;
646         if ( obj_load( object_base.str(), geometry.get(),
647                        NULL, NULL, NULL, light_pts.get(), true ) ) {
648             new_tile -> addChild( geometry.get() );
649         }
650
651     } else {
652         // ... or generate an ocean tile on the fly
653         SG_LOG(SG_TERRAIN, SG_INFO, "  Generating ocean tile");
654         osg::ref_ptr<osg::Group> geometry = new osg::Group;
655         Point3D c;
656         double br;
657         if ( SGGenTile( path_list[0], tile_bucket, &c, &br,
658                         globals->get_matlib(), geometry.get() ) ) {
659             center = c;
660             bounding_radius = br;
661             new_tile -> addChild( geometry.get() );
662         } else {
663             SG_LOG( SG_TERRAIN, SG_ALERT,
664                     "Warning: failed to generate ocean tile!" );
665         }
666     }
667
668
669     // now that we have a valid center, process all the objects
670     for (unsigned int j = 0; j < objects.size(); j++) {
671         const Object *obj = objects[j];
672
673         if (obj->type == OBJECT) {
674             SGPath custom_path = obj->path;
675             custom_path.append( obj->name );
676
677             osg::ref_ptr<osg::Group> geometry = new osg::Group;
678             osg::ref_ptr<osg::Group> vasi_lights = new osg::Group;
679             osg::ref_ptr<osg::Group> rwy_lights = new osg::Group;
680             osg::ref_ptr<osg::Group> taxi_lights = new osg::Group;
681
682             if ( obj_load( custom_path.str(),
683                            geometry.get(), vasi_lights.get(), rwy_lights.get(),
684                            taxi_lights.get(), NULL, false ) ) {
685
686                 if ( geometry -> getNumChildren() > 0 ) {
687                     new_tile -> addChild( geometry.get() );
688                 }
689
690                 if ( vasi_lights -> getNumChildren() > 0 )
691                     vasi_lights_transform -> addChild( vasi_lights.get() );
692
693                 if ( rwy_lights -> getNumChildren() > 0 )
694                     rwy_lights_transform -> addChild( rwy_lights.get() );
695
696                 if ( taxi_lights -> getNumChildren() > 0 )
697                     taxi_lights_transform -> addChild( taxi_lights.get() );
698             }
699
700
701         } else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
702             // object loading is deferred to main render thread,
703             // but lets figure out the paths right now.
704             SGPath custom_path;
705             if ( obj->type == OBJECT_STATIC ) {
706                 custom_path = obj->path;
707             } else {
708                 custom_path = globals->get_fg_root();
709             }
710             custom_path.append( obj->name );
711
712             osg::Matrix obj_pos;
713             WorldCoordinate( obj_pos, center, obj->lat, obj->lon, obj->elev, obj->hdg );
714
715             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
716             obj_trans->setMatrix( obj_pos );
717
718             // wire as much of the scene graph together as we can
719             new_tile->addChild( obj_trans );
720             pending_models++;
721
722             // push an entry onto the model load queue
723             FGDeferredModel *dm
724                 = new FGDeferredModel( custom_path.str(),
725                                        obj->path.str(),
726                                        tile_bucket,
727                                        this, obj_trans,
728                                        obj->type == OBJECT_SHARED );
729             FGTileMgr::model_ready( dm );
730
731
732         } else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
733             // load the object itself
734             SGPath custom_path = obj->path;
735             custom_path.append( obj->name );
736
737             osg::Matrix obj_pos;
738             WorldCoordinate( obj_pos, center, obj->lat, obj->lon, obj->elev, obj->hdg );
739
740             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
741             obj_trans->setMatrix( obj_pos );
742
743             osg::Node *custom_obj = 0;
744             if (obj->type == OBJECT_SIGN)
745                 custom_obj = SGMakeSign(globals->get_matlib(), custom_path.str(), obj->name);
746             else
747                 custom_obj = SGMakeRunwaySign(globals->get_matlib(), custom_path.str(), obj->name);
748
749             // wire the pieces together
750             if ( custom_obj != NULL ) {
751                 obj_trans -> addChild( custom_obj );
752             }
753             new_tile->addChild( obj_trans );
754
755         }
756         delete obj;
757     }
758
759
760     if ( new_tile != NULL ) {
761         terra_range->addChild( new_tile );
762     }
763
764     terra_transform->addChild( terra_range.get() );
765
766     // calculate initial tile offset
767     SGVec3d sgdTrans(center.x(), center.y(), center.z());
768     terra_transform->setTransform( sgdTrans );
769
770     // Add ground lights to scene graph if any exist
771     gnd_lights_transform = NULL;
772     gnd_lights_range = NULL;
773     if ( light_pts->size() ) {
774         SG_LOG( SG_TERRAIN, SG_DEBUG, "generating lights" );
775         gnd_lights_transform = new SGPlacementTransform;
776         gnd_lights_range = new osg::LOD;
777         gnd_lights_brightness = new osg::Switch;
778         osg::Node *lights;
779
780         lights = gen_lights( globals->get_matlib(), light_pts.get(), 4, 0.7 );
781         gnd_lights_brightness->addChild( lights );
782
783         lights = gen_lights( globals->get_matlib(), light_pts.get(), 2, 0.85 );
784         gnd_lights_brightness->addChild( lights );
785
786         lights = gen_lights( globals->get_matlib(), light_pts.get(), 1, 1.0 );
787         gnd_lights_brightness->addChild( lights );
788
789         gnd_lights_range->addChild( gnd_lights_brightness.get() );
790         gnd_lights_transform->addChild( gnd_lights_range.get() );
791         gnd_lights_transform->setTransform( sgdTrans );
792     }
793
794     // Update vasi lights transform
795     if ( vasi_lights_transform->getNumChildren() > 0 ) {
796         vasi_lights_transform->setTransform( sgdTrans );
797     }
798
799     // Update runway lights transform
800     if ( rwy_lights_transform->getNumChildren() > 0 ) {
801         rwy_lights_transform->setTransform( sgdTrans );
802     }
803
804      // Update taxi lights transform
805     if ( taxi_lights_transform->getNumChildren() > 0 ) {
806         taxi_lights_transform->setTransform( sgdTrans );
807     }
808 }
809
810 void
811 FGTileEntry::add_ssg_nodes( osg::Group *terrain_branch,
812                             osg::Group *gnd_lights_branch,
813                             osg::Group *vasi_lights_branch,
814                             osg::Group *rwy_lights_branch,
815                             osg::Group *taxi_lights_branch )
816 {
817     // bump up the ref count so we can remove this later without
818     // having ssg try to free the memory.
819     terrain_branch->addChild( terra_transform.get() );
820     globals->get_scenery()->register_placement_transform(terra_transform.get());
821
822     SG_LOG( SG_TERRAIN, SG_DEBUG,
823             "connected a tile into scene graph.  terra_transform = "
824             << terra_transform.get() );
825     SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
826             << terra_transform->getNumParents() );
827
828     if ( gnd_lights_transform.get() != NULL ) {
829         // bump up the ref count so we can remove this later without
830         // having ssg try to free the memory.
831         gnd_lights_branch->addChild( gnd_lights_transform.get() );
832         globals->get_scenery()->register_placement_transform(gnd_lights_transform.get());
833     }
834
835     if ( vasi_lights_transform.get() != NULL ) {
836         // bump up the ref count so we can remove this later without
837         // having ssg try to free the memory.
838         vasi_lights_selector->addChild( vasi_lights_transform.get() );
839         globals->get_scenery()->register_placement_transform(vasi_lights_transform.get());
840         vasi_lights_branch->addChild( vasi_lights_selector.get() );
841     }
842
843     if ( rwy_lights_transform.get() != NULL ) {
844         // bump up the ref count so we can remove this later without
845         // having ssg try to free the memory.
846         rwy_lights_selector->addChild( rwy_lights_transform.get() );
847         globals->get_scenery()->register_placement_transform(rwy_lights_transform.get());
848         rwy_lights_branch->addChild( rwy_lights_selector.get() );
849     }
850
851     if ( taxi_lights_transform.get() != NULL ) {
852         // bump up the ref count so we can remove this later without
853         // having ssg try to free the memory.
854         taxi_lights_selector->addChild( taxi_lights_transform.get() );
855         globals->get_scenery()->register_placement_transform(taxi_lights_transform.get());
856         taxi_lights_branch->addChild( taxi_lights_selector.get() );
857     }
858
859     loaded = true;
860 }
861
862
863 void
864 FGTileEntry::disconnect_ssg_nodes()
865 {
866     SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting ssg nodes" );
867
868     if ( ! loaded ) {
869         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
870     } else {
871         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile!  terra_transform = " << terra_transform.get() );
872     }
873         
874     // Unregister that one at the scenery manager
875     globals->get_scenery()->unregister_placement_transform(terra_transform.get());
876
877     // find the terrain branch parent
878     int pcount = terra_transform->getNumParents();
879     if ( pcount > 0 ) {
880         // find the first parent (should only be one)
881         osg::Group *parent = terra_transform->getParent( 0 ) ;
882         if( parent ) {
883             // disconnect the tile (we previously ref()'d it so it
884             // won't get freed now)
885             parent->removeChild( terra_transform.get() );
886         } else {
887             SG_LOG( SG_TERRAIN, SG_ALERT,
888                     "parent pointer is NULL!  Dying" );
889             exit(-1);
890         }
891     } else {
892         SG_LOG( SG_TERRAIN, SG_ALERT,
893                 "Parent count is zero for an ssg tile!  Dying" );
894         exit(-1);
895     }
896
897     // find the ground lighting branch
898     if ( gnd_lights_transform.get() ) {
899         // Unregister that one at the scenery manager
900         globals->get_scenery()->unregister_placement_transform(gnd_lights_transform.get());
901         pcount = gnd_lights_transform->getNumParents();
902         if ( pcount > 0 ) {
903             // find the first parent (should only be one)
904             osg::Group *parent = gnd_lights_transform->getParent( 0 ) ;
905             if( parent ) {
906                 // disconnect the light branch (we previously ref()'d
907                 // it so it won't get freed now)
908                 parent->removeChild( gnd_lights_transform.get() );
909             } else {
910                 SG_LOG( SG_TERRAIN, SG_ALERT,
911                         "parent pointer is NULL!  Dying" );
912                 exit(-1);
913             }
914         } else {
915             SG_LOG( SG_TERRAIN, SG_ALERT,
916                     "Parent count is zero for an ssg light tile!  Dying" );
917             exit(-1);
918         }
919     }
920
921     // find the vasi lighting branch
922     if ( vasi_lights_transform.get() ) {
923         // Unregister that one at the scenery manager
924         globals->get_scenery()->unregister_placement_transform(vasi_lights_transform.get());
925         pcount = vasi_lights_transform->getNumParents();
926         if ( pcount > 0 ) {
927             // find the first parent (should only be one)
928             osg::Group *parent = vasi_lights_transform->getParent( 0 ) ;
929             if( parent ) {
930                 // disconnect the light branch (we previously ref()'d
931                 // it so it won't get freed now)
932                 parent->removeChild( vasi_lights_transform.get() );
933             } else {
934                 SG_LOG( SG_TERRAIN, SG_ALERT,
935                         "parent pointer is NULL!  Dying" );
936                 exit(-1);
937             }
938         } else {
939             SG_LOG( SG_TERRAIN, SG_ALERT,
940                     "Parent count is zero for an ssg light tile!  Dying" );
941             exit(-1);
942         }
943     }
944
945     // find the runway lighting branch
946     if ( rwy_lights_transform.get() ) {
947         // Unregister that one at the scenery manager
948         globals->get_scenery()->unregister_placement_transform(rwy_lights_transform.get());
949         pcount = rwy_lights_transform->getNumParents();
950         if ( pcount > 0 ) {
951             // find the first parent (should only be one)
952             osg::Group *parent = rwy_lights_transform->getParent( 0 ) ;
953             if( parent ) {
954                 // disconnect the light branch (we previously ref()'d
955                 // it so it won't get freed now)
956                 parent->removeChild( rwy_lights_transform.get() );
957             } else {
958                 SG_LOG( SG_TERRAIN, SG_ALERT,
959                         "parent pointer is NULL!  Dying" );
960                 exit(-1);
961             }
962         } else {
963             SG_LOG( SG_TERRAIN, SG_ALERT,
964                     "Parent count is zero for an ssg light tile!  Dying" );
965             exit(-1);
966         }
967     }
968
969     // find the taxi lighting branch
970     if ( taxi_lights_transform.get() ) {
971         // Unregister that one at the scenery manager
972         globals->get_scenery()->unregister_placement_transform(taxi_lights_transform.get());
973         pcount = taxi_lights_transform->getNumParents();
974         if ( pcount > 0 ) {
975             // find the first parent (should only be one)
976             osg::Group *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->removeChild( taxi_lights_transform.get() );
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 }