]> git.mxchange.org Git - flightgear.git/blob - src/Main/positioninit.cxx
Reduce amount of log output at level=debug.
[flightgear.git] / src / Main / positioninit.cxx
1 // positioninit.cxx - helpers relating to setting initial aircraft position
2 //
3 // Copyright (C) 2012 James Turner  zakalawe@mac.com
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
19 #include "positioninit.hxx"
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #endif
24
25 // simgear
26 #include <simgear/props/props_io.hxx>
27 #include <simgear/structure/exception.hxx>
28 #include <simgear/structure/event_mgr.hxx>
29
30 #include "globals.hxx"
31 #include "fg_props.hxx"
32
33 #include <Navaids/navlist.hxx>
34 #include <Airports/runways.hxx>
35 #include <Airports/airport.hxx>
36 #include <Airports/dynamics.hxx>
37 #include <AIModel/AIManager.hxx>
38
39 using std::endl;
40 using std::string;
41
42 namespace flightgear
43 {
44     
45 /// to avoid blocking when metar-fetch is enabled, but the network is
46 /// unresponsive, we need a timeout value. This value is reset on initPosition,
47 /// and tracked through each call to finalizePosition.
48 static SGTimeStamp global_finalizeTime;
49 static bool global_callbackRegistered = false;
50
51 static void finalizePosition();
52   
53 // Set current tower position lon/lat given an airport id
54 static bool fgSetTowerPosFromAirportID( const string& id) {
55   const FGAirport *a = fgFindAirportID( id);
56   if (a) {
57     SGGeod tower = a->getTowerLocation();
58     fgSetDouble("/sim/tower/longitude-deg",  tower.getLongitudeDeg());
59     fgSetDouble("/sim/tower/latitude-deg",  tower.getLatitudeDeg());
60     fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
61     return true;
62   } else {
63     return false;
64   }
65   
66 }
67
68 struct FGTowerLocationListener : SGPropertyChangeListener {
69   void valueChanged(SGPropertyNode* node) {
70     string id(node->getStringValue());
71     if (fgGetBool("/sim/tower/auto-position",true))
72     {
73       // enforce using closest airport when auto-positioning is enabled
74       const char* closest_airport = fgGetString("/sim/airport/closest-airport-id", "");
75       if (closest_airport && (id != closest_airport))
76       {
77         id = closest_airport;
78         node->setStringValue(id);
79       }
80     }
81     fgSetTowerPosFromAirportID(id);
82   }
83 };
84
85 struct FGClosestTowerLocationListener : SGPropertyChangeListener
86 {
87   void valueChanged(SGPropertyNode* )
88   {
89     // closest airport has changed
90     if (fgGetBool("/sim/tower/auto-position",true))
91     {
92       // update tower position
93       const char* id = fgGetString("/sim/airport/closest-airport-id", "");
94       if (id && *id!=0)
95         fgSetString("/sim/tower/airport-id", id);
96     }
97   }
98 };
99
100 void initTowerLocationListener() {
101   fgGetNode("/sim/tower/airport-id",  true)
102   ->addChangeListener( new FGTowerLocationListener(), true );
103   FGClosestTowerLocationListener* ntcl = new FGClosestTowerLocationListener();
104   fgGetNode("/sim/airport/closest-airport-id", true)
105   ->addChangeListener(ntcl , true );
106   fgGetNode("/sim/tower/auto-position", true)
107   ->addChangeListener(ntcl, true );
108 }
109
110 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
111 {
112   SGGeod startPos(aStartPos);
113   if (aTargetHeading == HUGE_VAL) {
114     aTargetHeading = aHeading;
115   }
116   
117   if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
118     double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
119     offsetDistance *= SG_NM_TO_METER;
120     double offsetAzimuth = aHeading;
121     if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
122       offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
123       aHeading = aTargetHeading;
124     }
125     
126     SGGeod offset;
127     double az2; // dummy
128     SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
129     startPos = offset;
130   }
131   
132   // presets
133   fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
134   fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
135   fgSetDouble("/sim/presets/heading-deg", aHeading );
136   
137   // other code depends on the actual values being set ...
138   fgSetDouble("/position/longitude-deg",  startPos.getLongitudeDeg() );
139   fgSetDouble("/position/latitude-deg",  startPos.getLatitudeDeg() );
140   fgSetDouble("/orientation/heading-deg", aHeading );
141 }
142
143 // Set current_options lon/lat given an airport id and heading (degrees)
144 static bool setPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
145   if ( id.empty() )
146     return false;
147   
148   // set initial position from runway and heading
149   SG_LOG( SG_GENERAL, SG_INFO,
150          "Attempting to set starting position from airport code "
151          << id << " heading " << tgt_hdg );
152   
153   const FGAirport* apt = fgFindAirportID(id);
154   if (!apt) return false;
155   
156   SGGeod startPos;
157   double heading = tgt_hdg;
158   if (apt->type() == FGPositioned::HELIPORT) {
159     if (apt->numHelipads() > 0) {
160       startPos = apt->getHelipadByIndex(0)->geod();
161     } else {
162       startPos = apt->geod();
163     }
164   } else {
165     FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
166     fgSetString("/sim/atc/runway", r->ident().c_str());
167     startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
168     heading = r->headingDeg();
169   }
170
171   fgApplyStartOffset(startPos, heading, tgt_hdg);
172   return true;
173 }
174
175 // Set current_options lon/lat given an airport id and parkig position name
176 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos )
177 {
178   if ( id.empty() )
179     return false;
180   
181   // can't see an easy way around this const_cast at the moment
182   FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
183   if (!apt) {
184     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
185     return false;
186   }
187   FGAirportDynamics* dcs = apt->getDynamics();
188   if (!dcs) {
189     SG_LOG( SG_GENERAL, SG_ALERT,
190            "Airport " << id << "does not appear to have parking information available");
191     return false;
192   }
193   
194   ParkingAssignment pka;
195   double radius = fgGetDouble("/sim/dimensions/radius-m");
196   if ((parkpos == string("AVAILABLE")) && (radius > 0)) {
197     string fltType;
198     string acOperator;
199     SGPath acData;
200     try {
201       acData = globals->get_fg_home();
202       acData.append("aircraft-data");
203       string acfile = fgGetString("/sim/aircraft") + string(".xml");
204       acData.append(acfile);
205       SGPropertyNode root;
206       readProperties(acData.str(), &root);
207       SGPropertyNode * node = root.getNode("sim");
208       fltType    = node->getStringValue("aircraft-class", "NONE"     );
209       acOperator = node->getStringValue("aircraft-operator", "NONE"     );
210     } catch (const sg_exception &) {
211       SG_LOG(SG_GENERAL, SG_INFO,
212              "Could not load aircraft aircrat type and operator information from: " << acData.str() << ". Using defaults");
213       
214       // cout << path.str() << endl;
215     }
216     if (fltType.empty() || fltType == "NONE") {
217       SG_LOG(SG_GENERAL, SG_INFO,
218              "Aircraft type information not found in: " << acData.str() << ". Using default value");
219       fltType = fgGetString("/sim/aircraft-class"   );
220     }
221     if (acOperator.empty() || fltType == "NONE") {
222       SG_LOG(SG_GENERAL, SG_INFO,
223              "Aircraft operator information not found in: " << acData.str() << ". Using default value");
224       acOperator = fgGetString("/sim/aircraft-operator"   );
225     }
226     
227     string acType; // Currently not used by findAvailable parking, so safe to leave empty.
228     pka = dcs->getAvailableParking(radius, fltType, acType, acOperator);
229     if (pka.isValid()) {
230       fgGetString("/sim/presets/parkpos");
231       fgSetString("/sim/presets/parkpos", pka.parking()->getName());
232     } else {
233       SG_LOG( SG_GENERAL, SG_ALERT,
234              "Failed to find a suitable parking at airport " << id );
235       return false;
236     }
237   } else {
238     pka = dcs->getParkingByName(parkpos);
239     if (!pka.isValid()) {
240       SG_LOG( SG_GENERAL, SG_ALERT,
241                "Failed to find a parking at airport " << id << ":" << parkpos);
242       return false;
243     }
244   }
245   
246   fgApplyStartOffset(pka.parking()->geod(), pka.parking()->getHeading());
247   return true;
248 }
249
250
251 // Set current_options lon/lat given an airport id and runway number
252 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
253   if ( id.empty() )
254     return false;
255   
256   // set initial position from airport and runway number
257   SG_LOG( SG_GENERAL, SG_INFO,
258          "Attempting to set starting position for "
259          << id << ":" << rwy );
260   
261   const FGAirport* apt = fgFindAirportID(id);
262   if (!apt) {
263     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
264     return false;
265   }
266   
267   if (!apt->hasRunwayWithIdent(rwy)) {
268     SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
269            "Failed to find runway " << rwy <<
270            " at airport " << id << ". Using default runway." );
271     return false;
272   }
273   
274   FGRunway* r(apt->getRunwayByIdent(rwy));
275   fgSetString("/sim/atc/runway", r->ident().c_str());
276   SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
277   fgApplyStartOffset(startPos, r->headingDeg());
278   return true;
279 }
280
281
282 static void fgSetDistOrAltFromGlideSlope() {
283   // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
284   string apt_id = fgGetString("/sim/presets/airport-id");
285   double gs = fgGetDouble("/sim/presets/glideslope-deg")
286   * SG_DEGREES_TO_RADIANS ;
287   double od = fgGetDouble("/sim/presets/offset-distance-nm");
288   double alt = fgGetDouble("/sim/presets/altitude-ft");
289   
290   double apt_elev = 0.0;
291   if ( ! apt_id.empty() ) {
292     apt_elev = fgGetAirportElev( apt_id );
293     if ( apt_elev < -9990.0 ) {
294       apt_elev = 0.0;
295     }
296   } else {
297     apt_elev = 0.0;
298   }
299   
300   if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
301     // set altitude from glideslope and offset-distance
302     od *= SG_NM_TO_METER * SG_METER_TO_FEET;
303     alt = fabs(od*tan(gs)) + apt_elev;
304     fgSetDouble("/sim/presets/altitude-ft", alt);
305     fgSetBool("/sim/presets/onground", false);
306     SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
307            << alt  << " ft" );
308   } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
309     // set offset-distance from glideslope and altitude
310     od  = (alt - apt_elev) / tan(gs);
311     od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
312     fgSetDouble("/sim/presets/offset-distance-nm", od);
313     fgSetBool("/sim/presets/onground", false);
314     SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
315            << od  << " nm" );
316   } else if( fabs(gs) > 0.01 ) {
317     SG_LOG( SG_GENERAL, SG_ALERT,
318            "Glideslope given but not altitude or offset-distance." );
319     SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
320     fgSetDouble("/sim/presets/glideslope-deg", 0);
321     fgSetBool("/sim/presets/onground", true);
322   }
323 }
324
325
326 // Set current_options lon/lat given an airport id and heading (degrees)
327 static bool fgSetPosFromNAV( const string& id, const double& freq, FGPositioned::Type type )
328 {
329   FGNavList::TypeFilter filter(type);
330   const nav_list_type navlist = FGNavList::findByIdentAndFreq( id.c_str(), freq, &filter );
331   
332   if (navlist.empty()) {
333     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
334            << id << ":" << freq );
335     return false;
336   }
337   
338   if( navlist.size() > 1 ) {
339     std::ostringstream buf;
340     buf << "Ambigous NAV-ID: '" << id << "'. Specify id and frequency. Available stations:" << endl;
341     for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
342       // NDB stored in kHz, VOR stored in MHz * 100 :-P
343       double factor = (*it)->type() == FGPositioned::NDB ? 1.0 : 1/100.0;
344       string unit = (*it)->type() == FGPositioned::NDB ? "kHz" : "MHz";
345       buf << (*it)->ident() << " "
346       << std::setprecision(5) << (double)((*it)->get_freq() * factor) << " "
347       << (*it)->get_lat() << "/" << (*it)->get_lon()
348       << endl;
349     }
350     
351     SG_LOG( SG_GENERAL, SG_ALERT, buf.str() );
352     return false;
353   }
354   
355   FGNavRecord *nav = navlist[0];
356   fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
357   return true;
358 }
359
360 // Set current_options lon/lat given an aircraft carrier id
361 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
362   
363   // set initial position from runway and heading
364   SGGeod geodPos;
365   double heading;
366   SGVec3d uvw;
367   if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
368     double lon = geodPos.getLongitudeDeg();
369     double lat = geodPos.getLatitudeDeg();
370     double alt = geodPos.getElevationFt();
371     
372     SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
373            << carrier << " at lat = " << lat << ", lon = " << lon
374            << ", alt = " << alt << ", heading = " << heading);
375     
376     fgSetDouble("/sim/presets/longitude-deg",  lon);
377     fgSetDouble("/sim/presets/latitude-deg",  lat);
378     fgSetDouble("/sim/presets/altitude-ft", alt);
379     fgSetDouble("/sim/presets/heading-deg", heading);
380     fgSetDouble("/position/longitude-deg",  lon);
381     fgSetDouble("/position/latitude-deg",  lat);
382     fgSetDouble("/position/altitude-ft", alt);
383     fgSetDouble("/orientation/heading-deg", heading);
384     
385     fgSetString("/sim/presets/speed-set", "UVW");
386     fgSetDouble("/velocities/uBody-fps", uvw(0));
387     fgSetDouble("/velocities/vBody-fps", uvw(1));
388     fgSetDouble("/velocities/wBody-fps", uvw(2));
389     fgSetDouble("/sim/presets/uBody-fps", uvw(0));
390     fgSetDouble("/sim/presets/vBody-fps", uvw(1));
391     fgSetDouble("/sim/presets/wBody-fps", uvw(2));
392     
393     fgSetBool("/sim/presets/onground", true);
394     
395     return true;
396   } else {
397     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
398            << carrier );
399     return false;
400   }
401 }
402
403 // Set current_options lon/lat given an airport id and heading (degrees)
404 static bool fgSetPosFromFix( const string& id )
405 {
406   FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
407   FGPositioned* fix = FGPositioned::findFirstWithIdent(id, &fixFilter);
408   if (!fix) {
409     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
410     return false;
411   }
412   
413   fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
414   return true;
415 }
416
417 // Set the initial position based on presets (or defaults)
418 bool initPosition()
419 {
420   global_finalizeTime = SGTimeStamp(); // reset to invalid
421   if (!global_callbackRegistered) {
422     globals->get_event_mgr()->addTask("finalizePosition", &finalizePosition, 0.1);
423     global_callbackRegistered = true;
424   }
425     
426   double gs = fgGetDouble("/sim/presets/glideslope-deg")
427   * SG_DEGREES_TO_RADIANS ;
428   double od = fgGetDouble("/sim/presets/offset-distance-nm");
429   double alt = fgGetDouble("/sim/presets/altitude-ft");
430   
431   bool set_pos = false;
432   
433   // If glideslope is specified, then calculate offset-distance or
434   // altitude relative to glide slope if either of those was not
435   // specified.
436   if ( fabs( gs ) > 0.01 ) {
437     fgSetDistOrAltFromGlideSlope();
438   }
439   
440   
441   // If we have an explicit, in-range lon/lat, don't change it, just use it.
442   // If not, check for an airport-id and use that.
443   // If not, default to the middle of the KSFO field.
444   // The default values for lon/lat are deliberately out of range
445   // so that the airport-id can take effect; valid lon/lat will
446   // override airport-id, however.
447   double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
448   double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
449   if ( lon_deg >= -180.0 && lon_deg <= 180.0
450       && lat_deg >= -90.0 && lat_deg <= 90.0 )
451   {
452     set_pos = true;
453   }
454   
455   string apt = fgGetString("/sim/presets/airport-id");
456   string rwy_no = fgGetString("/sim/presets/runway");
457   bool rwy_req = fgGetBool("/sim/presets/runway-requested");
458   string vor = fgGetString("/sim/presets/vor-id");
459   double vor_freq = fgGetDouble("/sim/presets/vor-freq");
460   string ndb = fgGetString("/sim/presets/ndb-id");
461   double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
462   string carrier = fgGetString("/sim/presets/carrier");
463   string parkpos = fgGetString("/sim/presets/parkpos");
464   string fix = fgGetString("/sim/presets/fix");
465   SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
466   double hdg = hdg_preset->getDoubleValue();
467   
468   // save some start parameters, so that we can later say what the
469   // user really requested. TODO generalize that and move it to options.cxx
470   static bool start_options_saved = false;
471   if (!start_options_saved) {
472     start_options_saved = true;
473     SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
474     
475     opt->setDoubleValue("latitude-deg", lat_deg);
476     opt->setDoubleValue("longitude-deg", lon_deg);
477     opt->setDoubleValue("heading-deg", hdg);
478     opt->setStringValue("airport", apt.c_str());
479     opt->setStringValue("runway", rwy_no.c_str());
480   }
481   
482   if (hdg > 9990.0)
483     hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
484   
485   if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
486     // An airport + parking position is requested
487     if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
488       // set tower position
489       fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
490       fgSetString("/sim/tower/airport-id",  apt.c_str());
491       set_pos = true;
492     }
493   }
494   
495   if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
496     // An airport + runway is requested
497     if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
498       // set tower position (a little off the heading for single
499       // runway airports)
500       fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
501       fgSetString("/sim/tower/airport-id",  apt.c_str());
502       set_pos = true;
503     }
504   }
505   
506   if ( !set_pos && !apt.empty() ) {
507     // An airport is requested (find runway closest to hdg)
508     if ( setPosFromAirportIDandHdg( apt, hdg ) ) {
509       // set tower position (a little off the heading for single
510       // runway airports)
511       fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
512       fgSetString("/sim/tower/airport-id",  apt.c_str());
513       set_pos = true;
514     }
515   }
516   
517   if (hdg_preset->getDoubleValue() > 9990.0)
518     hdg_preset->setDoubleValue(hdg);
519   
520   if ( !set_pos && !vor.empty() ) {
521     // a VOR is requested
522     if ( fgSetPosFromNAV( vor, vor_freq, FGPositioned::VOR ) ) {
523       set_pos = true;
524     }
525   }
526   
527   if ( !set_pos && !ndb.empty() ) {
528     // an NDB is requested
529     if ( fgSetPosFromNAV( ndb, ndb_freq, FGPositioned::NDB ) ) {
530       set_pos = true;
531     }
532   }
533   
534   if ( !set_pos && !carrier.empty() ) {
535     // an aircraft carrier is requested
536     if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
537       set_pos = true;
538     }
539   }
540   
541   if ( !set_pos && !fix.empty() ) {
542     // a Fix is requested
543     if ( fgSetPosFromFix( fix ) ) {
544       set_pos = true;
545     }
546   }
547   
548   if ( !set_pos ) {
549     // No lon/lat specified, no airport specified, default to
550     // middle of KSFO field.
551     fgSetDouble("/sim/presets/longitude-deg", -122.374843);
552     fgSetDouble("/sim/presets/latitude-deg", 37.619002);
553   }
554   
555   fgSetDouble( "/position/longitude-deg",
556               fgGetDouble("/sim/presets/longitude-deg") );
557   fgSetDouble( "/position/latitude-deg",
558               fgGetDouble("/sim/presets/latitude-deg") );
559   fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
560   
561   // determine if this should be an on-ground or in-air start
562   if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
563     fgSetBool("/sim/presets/onground", false);
564   } else {
565     fgSetBool("/sim/presets/onground", true);
566   }
567   
568   fgSetBool("/sim/position-finalized", false);
569     
570   return true;
571 }
572   
573 bool finalizeMetar()
574 {
575   double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
576   string apt = fgGetString("/sim/presets/airport-id");
577   string rwy = fgGetString("/sim/presets/runway");
578   double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
579   string parkpos = fgGetString( "/sim/presets/parkpos" );
580   bool onground = fgGetBool( "/sim/presets/onground", false );
581   // this logic is taken from former startup.nas
582   bool needMetar = (hdg < 360.0) && !apt.empty() && (strthdg > 360.0) &&
583   rwy.empty() && onground && parkpos.empty();
584   
585   if (needMetar) {
586     // timeout so we don't spin forever if the network is down
587     if (global_finalizeTime.elapsedMSec() > fgGetInt("/sim/startup/metar-fetch-timeout-msec", 10000)) {
588       SG_LOG(SG_GENERAL, SG_WARN, "finalizePosition: timed out waiting for METAR fetch");
589       return true;
590     }
591     
592     if (!fgGetBool( "/environment/metar/valid" )) {
593       return false;
594     }
595     
596     SG_LOG(SG_ENVIRONMENT, SG_INFO,
597            "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
598     setPosFromAirportIDandHdg( apt, hdg );
599     // fall through to return true
600   } // of need-metar case
601   
602   return true;
603 }
604   
605 void finalizePosition()
606 {
607   // first call to finalize after an initPosition call
608   if (global_finalizeTime.get_usec() == 0) {
609     global_finalizeTime = SGTimeStamp::now();
610   }
611   
612   bool done = true;
613   
614     /* Scenarios require Nasal, so FGAIManager loads the scenarios,
615      * including its models such as a/c carriers, in its 'postinit',
616      * which is the very last thing we do.
617      * flightgear::initPosition is called very early in main.cxx/fgIdleFunction,
618      * one of the first things we do, long before scenarios/carriers are
619      * loaded. => When requested "initial preset position" relates to a
620      * carrier, recalculate the 'initial' position here 
621      */
622     std::string carrier = fgGetString("/sim/presets/carrier","");
623     if (!carrier.empty())
624     {
625         SG_LOG(SG_GENERAL, SG_INFO, "finalizePositioned: re-init-ing position on carrier");
626         // clear preset location and re-trigger position setup
627         fgSetDouble("/sim/presets/longitude-deg", 9999);
628         fgSetDouble("/sim/presets/latitude-deg", 9999);
629         initPosition();
630     } else {
631         done = finalizeMetar();
632     }
633   
634     fgSetBool("/sim/position-finalized", done);
635     if (done) {
636         globals->get_event_mgr()->removeTask("finalizePosition");
637         global_callbackRegistered = false;
638     }
639 }
640     
641 } // of namespace flightgear