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